facebook twitter hatena line email

Php/reflection

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

php_refrectionとは

クラスの情報を取得・書き換えできるクラス。php5からコアに追加された


クラス情報取得サンプル

class User
{
    private $_name;
    private $_birthday;
    public function __construct($name, $birthday)
    {
        $this->_name = $name;
        $this->_birthday = $birthday;
    }
}
$reflClass = new ReflectionClass('User');
echo $reflClass->getName(); // User
echo $reflClass->getNamespaceName(); // 
echo $reflClass->getShortName(); // User
echo $reflClass->getFileName(); // /var/www/test/sample.php


privateでもアクセスできるようにmethodを書き換えるサンプル

class User
{
    private $_name;
    private $_birthday;
    public function __construct($name, $birthday)
    {
        $this->_name = $name;
        $this->_birthday = $birthday;
    }
    public function getName()
    {
        return $this->_name;
    }
    private function getBirthday()
    {
        return $this->_birthday;
    }
}
$user = new User("taro", "2000-10-10");
$reflectionClass = new ReflectionClass('User');
$reflMethod = $reflectionClass->getMethod('getBirthday');
$reflMethod->setAccessible(true);
echo $reflMethod->invoke($user); // 2000-10-10

privateでもアクセスできるようにpropertyを書き換えるサンプル

$reflectionClass = new ReflectionClass('User');
$reflectionProperty = $reflectionClass->getProperty('_name');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($user, 'sato');
echo $reflectionProperty->getValue($user); // sato

ReflectionMethodを使ってprivateのmethodをそのままロードする方法

$reflMethod = new ReflectionMethod('User', 'getBirthday');
$reflMethod->setAccessible(true);
echo $reflMethod->invoke($user); // 2000-10-10

privateのpropertyを書き換えた後、methodを実行するサンプル

$reflectionClass = new ReflectionClass('User');
$reflectionProperty = $reflectionClass->getProperty('_name');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($user, 'sato');
$reflMethod = $reflectionClass->getMethod('getBirthday');
echo $reflMethod->invoke($user); // 2000-10-10