What is '&new' ?
Posted by John_Moylan (John_Moylan), 8 September 2002I've seen this in the PHP cookbook in the classes section. It was used to call an instance of an object.
Whats bothering me is why is 'new' prefixed with & ?
I've managed to whittle it down to be realted to references, but no real detailed explaination was forthcoming.
Posted by admin (Graham Ellis), 9 September 2002Hi, John. I've just had a look at "PHP Developer's Cookbook" which is on my shelf and I couldn't spot the "&" there - but then there are many books on PHP so perhaps it's another book, or perhaps (very likely at this hour of the morning) I don't yet have both eyes open! So ... trying to cut a long story to midlength - I may be answering the wrong question ....
Here's an example of a piece of PHP that calls a function called dressing; it's called with one, two or three parameters, the first one of which is a variable containing a string of text which the users wants "dressed" in a certain colour and font. Note particularly that the PHP is written to return the dressed string IN PLACE OF the incoming variable - in other words, it's designed to change the incoming variable.
So far so good, but PHP defaults to a "call by value" system where a copy of the contents of a variable are passed into a function. This default behaviour is much safer for functions written by newcomers, as it means that the function won't damage anything in the calling code. It's rather like to asking to borrow a map from me, and me giving you a copy. Then when you write all over the map that you have (the copy!), you're not damaging my original.
If you add an & in front of the varaible name in a PHP function declaration, you change the behaviour to "call by name". In this situation, it's a reference to (i.e. a use of) the original that the function picks up, so that any changes made to the incoming varaible are reflected back in the variable within the calling code. Thus, the function looks llike:
and actually changes the incoming value via altering the $text variable.
PHP is unusual in that you don't have to take any corresponding action in the call to indicate that you're calling by name, as you would in other languages.
In C, you use an & in the calling code to pass the address of a variable, and an * in the function to indicate the contents of an address variable. In perl, you would use \ for the address of, and $ for the contents of. In Tcl, you simple leave the $ off the variable name in your call, then use upvar (ask on the Tcl board if you wonder!) within the proc.
Hope this is interesting ... hope it's relevant too, come to think of it. If I've answered the wrong question here, please do post up some sample code so that I can see what you're looking at!
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: email@example.com • WEB: http://www.wellho.net • SKYPE: wellho