Search code examples
phplamp

Magic method to run when object is referenced by a variable in an echo statement


In PHP does such a magic method automatically run when a variable referencing an object is in an echo statement?


Solution

  • I am sorry, I had quite a difficulty understanding what you're asking. I believe you want the __toString() method:

    The __toString() method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.

    Here's a quick example:

    class A
    {
        public function __toString()
        {
            return 'banana';
        }
    }
    
    $a = new A();
    echo $a;
    

    This will print out banana