1

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?

4
  • 4
    What exactly are you trying to do? Do you have an example of real-world code that would make use of this? Commented Aug 30, 2010 at 4:30
  • Look.Now $obj is an object array. I want to define a default value like $obj to call. I don't want touch any array object. When I write $obj it will return default value, when I write $obj->obj1 it will return $obj1. Commented Aug 30, 2010 at 4:35
  • I don't have idea what you're trying to do. Please describe what actually you want to achieve. Maybe you should create some kind of collection (like Java collections) that stores other objects and implements __toString() method? Commented Aug 30, 2010 at 4:39
  • Okay. In the question $obj->obj1 is $obj1, $obj->obj2 is $obj2, ... But with all those objects I want to define a default value like index to $obj.For example when I use $obj without any child, it will return a string. Commented Aug 30, 2010 at 4:45

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

4 Comments

Is the any method instead of using class?
@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.
@sundowatch no a class is the only way to since it can use the __toString() magic method.
Okay. I understood it. I used __toString() method. Thanks.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.