4

我对 PHP 比较陌生,但已经意识到它是一个强大的工具。所以在这里原谅我的无知。

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

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

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

例子

class String {
     public function __construct() {  }

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

}

用法

$str = new String(...);
print($str); //executes toString()
4

3 回答 3

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;
?>
于 2012-01-26T14:33:15.133 回答
2

__toString()打印对象时调用,即 echo $str。

__call()是任何类的默认方法。

于 2012-01-26T14:43:30.757 回答
1

要么将 toString 函数代码放在 __construct 中,要么指向 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');
于 2012-01-26T14:36:01.600 回答