Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 335
IEnumerable Avatar asked Dec 12 '22 05:12

IEnumerable


1 Answers

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;
?>
like image 69
Rene Pot Avatar answered Dec 26 '22 18:12

Rene Pot