この前の質問__get()
のようなエラー メッセージが表示されないようにするために、以下のようにクラスを変更することにしました。
class property
{
public function __get($name)
{
return isset($this->$name) ? $this->$name : new property;
}
}
class objectify
{
public function array_to_object($array = array(), $property_overloading = false)
{
# if $array is not an array, let's make it array with one value of former $array.
if (!is_array($array)) $array = array($array);
# Use property overloading to handle inaccessible properties, if overloading is set to be true.
# Else use std object.
if($property_overloading === true) $object = new property();
else $object = new stdClass();
foreach($array as $key => $value)
{
$key = (string) $key ;
$object->$key = is_array($value) ? self::array_to_object($value, $property_overloading) : $value;
}
return $object;
}
}
$object = new objectify();
$type = null;
$type = $object->array_to_object($type,true);
var_dump($type->a->b->c);
最終的にこの結果が得られます
object(property)#3 (0) { }
しかし、まだ完璧ではありません。私の理解では、上記のソリューションはオブジェクトを次のようにチェーンで処理します。
$type = object{}->object{}->object{}
だから私はそれが最後のチェーンであり、それが空であるかどうかを見つけることができるのだろうかnull
?
$type = object{}->object{}->NULL
PHPで可能ですか?
編集:
プロパティ クラスがインスタンス化された回数を数えるというアイデアを思いついたのですが、
class property
{
public static $counter = 0;
function __construct() {
self::$counter++;
}
public function __get($name)
{
if(isset($this->$name))
{
return $this->$name;
}
elseif(property::$counter < 3)
{
return new property;
}
else
{
return null;
}
}
}
しかし、私の唯一の問題は、数値を3
動的にする方法です。何か案は?