Php/reflection
提供: 初心者エンジニアの簡易メモ
2015年5月20日 (水) 03:13時点における127.0.0.1 (トーク)による版 (ページの作成:「==php_refrectionとは== クラスの情報を取得・書き換えできるクラス。php5からコアに追加された ==クラス情報取得サンプル== clas...」)
目次
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
