I want to convert my class object to array. I have already asked a question about how to convert object to array.
But While doing this I was wondering if we can do something like this:
$arrObj = (array) $objectOfMyClass;
As I know it will convert object to array but if there is some user defined function in which I can control this behavior and allow few of the members to be passed as array keys.
For Exmaple lets Say I have a class:
class Property {
private $x;
protected $y;
public $z;
public function someFunction() {
//some code
}
public function someFunction1() {
//some code1
}
}
$objArray = (array) (new Property());
echo '<pre>', print_r($objArray, true), '</pre>';
Output:
Array
(
[Propertyx] =>
[*y] =>
[z] =>
)
But I dont want this output I want to alter this output and want output like this:
Array
(
[z] =>
)
or
Array
(
[y] =>
[z] =>
)
So there must be some way through which I can call a user defined function when some one tried to type cast my class objects like this:
class Property {
....
....
public function __toArray() {
return <'only public or protected members'>
}
}
When some one use following statement:
$objArray = (array) (new Property());
It should invoke __toArray method. Same like __toString.
If anyone knows any ways to do something like this please help me.
If there are any other solutions out there which may result into the same output would be really helpful.
Thanks in Advance.