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 に答える