Jump to content

Adding array items if array is an object property


kixe
 Share

Recommended Posts

Tried to add an item to an array, which is a page property. The common way doesn't work. Is there a PHP expert out there who can explain that to me? Thanks.

$page->prop = array('a','b','c');
$page->prop[] = 'd';
var_dump($page->prop);
// output: array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" }

$page->prop = array('a','b','c');
$page->prop = array_merge($page->prop, array('d'));
var_dump($page->prop);
// output: array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string(1) "d" }

 

Link to comment
Share on other sites

I could be wrong but.. you are trying to modify a protected property directly and that the reason. As you know, you can't modify directly a protected property outside his class. and you have to use a setter to modify this variable.

Try #2 :

Generally speaking, the properties on an object will be set to protected and so attempting to access a property in this way will cause an error.

So what actually happen here. The property $page->prop doesn't really exist and a magic __set() is written, and also a magic __get() function is written which will return a value when you read from this property. PHP will automatically call it for you when you try to access a property that is not one of the object’s public properties. If you try to set a property that is not accessible, the __set() magic method will be triggered. 

Its important to stipulate here that the return of this __get() magic function is a VALUE and not a reference (&__get()). If it was a reference that have been be returned by the function, you could modify the returned property.

Assigning a variable directly to it can work if there is a corresponding magic __set(), but here you cannot modify it, since its actually a function which return value (and not a reference!) : the key is here

So, basically, we can say that you are trying to do the following :   $page->__get('prop')[] = ['d'], which doesn't mean anything, and PHP will trigger a notice of type : Indirect modification of overloaded property

 

Edited by flydev
try #2
  • Like 4
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...