Web就活日記

愛と夢と人生について書きます

magic method

phpのマジックメソッドについて挙動を確認してみました。
とりあえずは代表的なもののみをピックアップ。

<?php

class MagicMethod {

    private $data_ = array();

    public function __construct() {
        echo "call construct \n";
    }   

    public function __destruct() {
        echo "call destruct \n";
    }   

    public function __get( $key ) { 
        echo "call __get \n";
        return $this->data_[ $key ];
    }   

    public function __set( $key, $name ) { 
        $this->data_[ $key ] = $name;
        echo "call __set \n";
    }   

    public function __toString() {
        return __CLASS__;
    }   

    public function __call( $name, $arguments ) {
        $arg = implode( "," , $arguments );
        echo "call func class = $name  arg = $arg \n";
    }

}

//__construct
$magic = new MagicMethod();

//__call
$magic->magic( 'test', array( 'arg1', 'arg2' ) );

//__set
$magic->key = 'test';

// __get
echo $magic->key . "\n";

//__toString
echo $magic . "\n";

//__destruct
unset( $magic );

echo "process is finished \n";

以下は出力結果です。

call construct 
call func class = magic  arg = test,Array 
call __set 
call __get 
test
MagicMethod
call destruct 
process is finished 

スポンサーリンク