4

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()

3 Answers 3

10

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;
?>
Sign up to request clarification or add additional context in comments.

3 Comments

Isn't this just used as a way to define how the class should be returned when requested as a string?
I like this method, very clear and simple, cant believe google didnt find it. Thankyou so much..
Gotcha, seems that I didn't interpret the question the right way. :D
2

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

__call() is the default method for any class.

Comments

1

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');

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.