Search code examples
phpobject-to-string

PHP Assigning a default Function to a class


Im relatively new to PHP but have realized it is a powerfull tool. So excuse my ignorance here.

I want to create a set of objects with default functions.

So rather than calling a function in the class we can just output the class/object variable and it could execute the default function i.e toString() method.

The Question: Is there a way of defining a default function in a class ?

Example

class String {
     public function __construct() {  }

     //This I want to be the default function
     public function toString() {  }

}

Usage

$str = new String(...);
print($str); //executes toString()

Solution

  • There is no such thing as a default function but there are magic methods for classes which can be triggered automatically in certain circumstances. In your case you are looking for __toString()

    http://php.net/manual/en/language.oop5.magic.php

    Example from Manual:

    // 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;
    ?>