|
Posted by Henk verhoeven on 04/12/07 22:34
Hi amygdala,
In fact only variables are referenced when using &, not objects or values.
There are four places where you can put the & sign, each has a different
effect:
1. After the = of an assignment,
2. Before the name of a function in the function declaration
3. Before the name of a parameter declaration in a function declaration
4. Before the name of a variable in a function call.
The first makes the assignment assign a reference instead of a value,
The second makes a function return by reference instead of by value,
The third makes a parameter to be passed by reference instead of by
value whenever the function is called
The fourth forces a parameter to be passed by reference only for the
specific function call.
The fourh is depricated and will trigger a warning if
allow_call_time_pass_reference = Off in php.ini.
If you use php5 objects are automatically passed by reference, you don't
need the & sign for that. In php4 there is no choice you can only mimic
object references by referencing variables that hold objects. This can
be tricky, if you can you better use php5.
Using references inapropriately may cause crashes and reference
anomalies*. For this reason php 4.4 and php 5.1 trigger notifications if
a value instead of a variable is assigned or passed by reference. If you
use references consider to use one one of these with error_reporting
set to E_ALL.
Greetings,
Henk Verhoeven,
www.phpPeanuts.org
* http://www.phppeanuts.org/site/index_php/Pagina/167/reference+anomaly.html
calling the following and using the result has a good chance to crash php:
function &badOne() {
return $uninitializedVariable;
}
amygdala schreef:
> I'm trying to figure out the correct use of references.
>
> Lets say I have a class Validator and a class User. And I want to let a User
> instance be an referenced object in Validator. Where would the best place be
> to put the & sign, and why? (See the /* */ comments inside code)
>
> class Validator
> {
> public function __construct( /* here? */ $caller )
> {
> $this->class =/* here? */ $caller;
> }
> }
>
> class User
> {
> $private validator = NULL;
> public function __construct()
> {
> $this->validator = new Validator( /* or here? */ $this );
> }
> }
>
> Also, what would happen if were to put & signs in multiple places sprecified
> in this particular example? Would it be redundant?
>
> Thank you for any insight.
>
>
[Back to original message]
|