views:

30

answers:

2

I have a function which returns object array like that:

<?php

function sth()
{
   return (object) array(
     "obj1" => $obj1,
     "obj2" => $obj2,
     "obj3" => $obj3
   );
}

$obj = sth();
echo $obj;

?>

Here I want to define $obj's default value.It will return default value instead of $obj1,$obj2,$obj3.

How can I define a default value?

A: 

Create class containing array of your objects as a property. and in __toString() method return anything you desire.

Shota Bakuradze
+2  A: 

You need to add actual functionality to the object to achieve this. Simply casting an array to an object only creates an object that holds some values, it is not very different from an array. There's no notion of "default values" for either arrays or objects, the only way to simulate this concept is by implementing it using magic methods, in this case __toString. As such, you need to create a class akin to this:

class ObjectWithDefaultValue {
    public function __construct($params) {
        // assign params to properties
        ...
    }

    public function __toString() {
        return $this->obj1;
    }
}

function sth() {
   $obj = new ObjectWithDefaultValue(array(
     "obj1" => $obj1,
     "obj2" => $obj2,
     "obj3" => $obj3
   ));

   return $obj;
}

$obj = sth();
echo $obj;
deceze
Is the any method instead of using class?
sundowatch
@sundo You will need to add a `__toString` method to the object somehow, if you want to use it this way. A class is the only realistic way to do that.
deceze
@sundowatch no a class is the only way to since it can use the __toString() magic method.
Ben Rowe
Okay. I understood it. I used __toString() method. Thanks.
sundowatch