No, it's not possible to do that because one can't extent built-in things like array
. There are some ways to achieve parts of what you want though:
Printing out custom data on var_dump()
This is a feature was introduced in PHP 5.6 with the __debugInfo()
magic method.
class Hello {
public function __debugInfo(){
return ['one','two','three'];
}
}
var_dump(new Hello);
This would output:
object(Hello)#1 (3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
string(5) "three"
}
Acting like an array
While you can't make your objects be an array (that is, extend it), they can behave like arrays if you implement the ArrayAccess
interface:
class Hello implements ArrayAccess {
private $data = [];
public function offsetExists($offset) {
return isset($this->data[$offset]);
}
/* insert the rest of the implementation here */
}
And then you can use it like an array:
$fake_array = new Hello();
$fake_array['foo'] = 'bar';
echo $fake_array['foo'];
Note that you can't pass classes that implement this interface into methods hinted with array
.
It is not possible to act like any other primitive data type unfortunately. If you want ultimate flexibility, you will have to look at things like Python and Scala. In PHP you will need to use some pattern like a getData()
and setData()
interface for the wrapping object.