I am looking for a way to intercept the action in array_push
, because when it will be retrieve it each value of the array has another info like:
class ClassName {
var $test = array();
function __set($attr, $value) {
$this->$attr = 'My extra value'.$value;
}
function index(){
array_push($this->test, "some val");
array_push($this->test, "some other val");
print_r($this->test);
}
}
$o = new ClassName();
$o->index();
And expected to get something like:
Array
(
[0] => My extra value some val
[1] => My extra value some other val
)
But i get:
Array
(
[0] => some val
[1] => some other val
)
Thanks to all
To achieve what you're looking for, I suggest you create yourself a function that prefixes any value independent to it's use:
You can then make use of that function inside the
index()
function:Instead of using an array, you can use a class that implements the ArrayAccess interface. This way you have full control over what occurs when you append to the array.
http://php.net/manual/en/class.arrayaccess.php
The drawback is that not all array functions will work on the object (ie sorting etc), but you can push like so:
The alternative is to simply make a wrapper function for adding to the array.
I don't totally understand what you're asking, but are you trying to do this:
That will allow you to setup your own output nicely. Because array_push() will throw on another nested level.
Update: Maybe something along these lines?
The PHP manual says the following about magic methods:
Because the
test
property is inside the method and the function that is accessing it is inside the method, the function will see the variable directly and will not use the magic setter.Additionally, even if you try to use array_push on the magic setter outside the class itself, that still will not work. You will get the error
array_push() expects parameter 1 to be array, object given
.If you want to support array_push, you should write your own
push($item)
method:or:
if you want to support pushing multiple items at once.
From the PHP manual:
This is only called on reading/writing inaccessible properties. Your property however is public, which means it is accessible. Changing the access modifier to protected solves the issue.
Try this: