Question

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()
Was it helpful?

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

OTHER TIPS

Either put the toString function code inside __construct, or point to toString.

class String {
     public function __construct( $str ) { return $this->toString( $str ); }

     //This I want to be the default function
     public function toString( $str ) { return (str)$str; }
}

print new String('test');

__toString() is called when you print your object, i.e. echo $str.

__call() is the default method for any class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top