PHP为类分配默认函数

IEn*_*ble 4 php object-to-string

我相对较新的PHP,但已意识到它是一个强大的工具.所以请原谅我的无知.

我想创建一组具有默认功能的对象.

因此,不是在类中调用函数,而是可以输出类/对象变量,它可以执行默认函数即toString()方法.

问题: 有没有办法在类中定义默认函数?

class String {
     public function __construct() {  }

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

}
Run Code Online (Sandbox Code Playgroud)

用法

$str = new String(...);
print($str); //executes toString()
Run Code Online (Sandbox Code Playgroud)

Ren*_*Pot 10

没有默认函数这样的东西,但是在某些情况下可以自动触发类的魔术方法.在你的情况下,你正在寻找__toString()

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

手册示例:

// 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;
?>
Run Code Online (Sandbox Code Playgroud)

  • 是的,但这似乎是这里的问题 (2认同)