PHPで同じようなのを作ってみた
前のエントリの PHP 版を作ってみようと思ったら出来なかった。
ReflectionProperty#setAccessibleは5.3.0以降なのね。MoteGramのActionクラスのフィールドはpublicフィールド推奨だなぁ。
private/protected なプロパティに対して行うとReflectionExceptionをthrowするので握り潰してます。例外処理のポリシーも考えておかないとなぁ。
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of ReflectionUtil * * @author devworks */ class ReflectionUtil { public static function getClass($obj) { $name = get_class($obj); return new ReflectionClass($name); } public static function getProperty($obj, $name) { $clazz = self::getClass($obj); return $clazz -> getProperty($name); } } ?>
<?php require_once 'ReflectionUtil.php'; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of FeildUtil * * @author devworks */ class PropertyUtil { public static function get($obj, $name) { if ($obj === null || ($name === null || strlen($name) === 0) ) { return null; } $property = ReflectionUtil::getProperty($obj, $name); try { return $property -> getValue($obj); } catch (ReflectionException $e) { return null; } } public static function set($obj, $name, $value) { if ($obj === null || ($name === null || strlen($name) === 0) ) { return; } $property = ReflectionUtil::getProperty($obj, $name); try { $property -> setValue($obj, $value); } catch (ReflectionException $e) { return; } } } ?>