通过引用分配失败,语法错误[关闭]

I have a class instance $obj = new class. obj is actually a variable from another object so it's more like $obj1->obj2->obj3 = new class. This is making my code a little confusing so I want to do something like:

$var =& $obj1->obj2->obj3 = new class

and then start using this instance as

$var->method() or $var->name = 'abc'.

When using it like $var = $obj1->obj2->obj3 = new class it works just fine but I was thinking about the memory I could save (as the object is quite large and duplicating it would not be advisable). I'm not sure if this is an issue or if it actually necessary to assign by reference or if PHP takes this into consideration.

I forgot to mention, using $var =& $obj1->obj2->obj3 = new class results in:

Parse error: syntax error, unexpected '='

When you do

$var = new stdClass();
$var2 = $var; 

$var2 is actually a reference to $var. This is because PHP passes classes by reference. So you aren't actually making a new copy. So you can assign it to your shorter variable and reduce the typing.

Doing the following will assign the same object to $obj1->obj2->obj3 and $var.

$obj1->obj2->obj3 = new class;
$var = $obj1->obj2->obj3;

Fields initialization should be done in constructor or another class method.

You can do initialization like usual (it's one time)

$this->obj2->obj3 = new Class();

After that in the outer code you can do

$var = $obj1->obj2->obj3;
$var->method;

Also please note, using nested objects complicates the system and too deep nesting is not recommended.

  • As of PHP 5, objects are always passed by reference. In PHP 4 $a = new obj; would in fact duplicate the object, once during creation, and another during assignment to $a, this is no longer the case.
  • Regular variables in PHP are copy on write, so even $a = 'fred'; $b = $a; hasn't doubled the memory usage (yet)
  • In general with PHP, until you run into problems it's best to just let the language do the work, rather than trying to out-think it :)

To answer the question about the syntax error, the reason you're getting a syntax error is because you're trying to assign a reference to something that's not a variable.

This code:

$var =& $obj1->obj2->obj3 = new class

gets evaluated like this (because the = operator has right associativity):

$var =& ($obj1->obj2->obj3 = new class)

which doesn't work because you can't create a reference to an expression.

As far as creating a reference to the object rather than a copy, that depends on which version of PHP you're running. In PHP5, objects are (effectively) always passed by reference.