-2

So say I have the following code,

$obj = new foo();
echo $obj;

class foo {
    public function __construct()
    {
        return 'a';
    }
}

How do I make $obj echo the string 'a'?

How do I make $obj refer to or equal what is returned by the object/class?

Need to return a value from a __construct(), and also a normal private function within another class. For example:

$obj2 = new foo2();
echo $obj2;

class foo2 {
    public function __construct()
    {
        bar();
    }

    private bar() 
    {
        return 'a';
    }
} 

Thanks!

2
  • I just want to mention here that this is highly uncommon(even if possible) and I cant think of any use case at all why someone would need that. Commented Aug 2, 2013 at 5:04
  • did you at least TRY to read the fine manual before posting this? Commented Aug 2, 2013 at 11:18

2 Answers 2

2

you can use the magic __toString() method to convert your class to a representing string. You should not return something in your constructor, __toString() is automaticly called if you try to use your instance as string (in case of echo).

from php.net:

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo)
    {
        $this->foo = $foo;
    }

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

$class = new TestClass('Hello');
echo $class;
?>

http://www.php.net/manual/en/language.oop5.magic.php#object.tostring

Sign up to request clarification or add additional context in comments.

Comments

2

Constructors in PHP are more like initialisation functions; their return value is not used, unlike JavaScript for instance.

If you want to change the way objects are normally echoed you need to provide the magic __toString() method:

class foo 
{
    private $value;

    public function __construct()
    {
        $this->value = 'a';
    }

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

A private method that would return the value can be used in a similar manner:

class foo2
{
    private function bar()
    {
        return 'a';
    }

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

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.