PHPオブジェクト向け__tostring()と_invoke()
6149 ワード
__tostring()マジックメソッド
オブジェクトを文字列として使用すると、メソッドが自動的に呼び出され、オブジェクトが文字列に変換された後の結果を示す文字列を返すことができます.このマジックの方法はよく使われる.注:このメソッドが定義されていない場合、オブジェクトは文字列として使用できません.
クラスには定義されていません_tostring()メソッドの例:
3つのエラー内容はそれぞれ
クラス内の定義_tostring()メソッド
実行結果
__invoke()マジックメソッド
このメソッドは、オブジェクトを関数として使用すると自動的に呼び出されます.通常はお勧めしません.
オブジェクトを文字列として使用すると、メソッドが自動的に呼び出され、オブジェクトが文字列に変換された後の結果を示す文字列を返すことができます.このマジックの方法はよく使われる.注:このメソッドが定義されていない場合、オブジェクトは文字列として使用できません.
クラスには定義されていません_tostring()メソッドの例:
ini_set('display_errors', 1);
class A{
public $name;
public $age;
public $sex;
function __construct($name, $age, $sex){
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
}
$obj1 = new A(' ', 15, ' ');
echo $obj1; //echo , ,
$v1 = "abc" . $obj1; //. ,
$v2 = "abx" + $obj1; //+ ,
?>
3つのエラー内容はそれぞれ
Catchable fatal error: Object of class A could not be converted to string
Catchable fatal error: Object of class A could not be converted to string
Notice: Object of class A could not be converted to int
クラス内の定義_tostring()メソッド
ini_set('display_errors', 1);
class A{
public $name;
public $age;
public $sex;
function __construct($name, $age, $sex){
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
function __tostring(){
$str = " :" . $this->name;
$str .= " :" . $this->age;
$str .= ", :" . $this->sex;
return $str; // “ ”
}
}
$obj1 = new A(' ', 15, ' ');
echo $obj1; // __tostring(),
?>
実行結果
: :15, :
__invoke()マジックメソッド
このメソッドは、オブジェクトを関数として使用すると自動的に呼び出されます.通常はお勧めしません.
class A{
function __invoke(){
echo "
, !";
}
}
$obj = new A();
$obj(); // :__invoke()