问题
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()
回答1:
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;
?>
回答2:
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');
回答3:
__toString()
is called when you print your object, i.e. echo $str.
__call()
is the default method for any class.
来源:https://stackoverflow.com/questions/9019611/php-assigning-a-default-function-to-a-class