我正在尝试创建一个包含一组属性的类。它将像这样使用:
$class = new test_class();
$class->property;
$class->second_property;
基本上,如果属性存在,则为真,如果属性不存在,则为假。属性没有价值,只有存在。
现在,我想做这样的事情:
$class = new test_class();
var_dump($class->property); // false - property does not exist
var_dump($class->second_property); // true - second_property exists
var_dump( (bool) $class); // true
因此,即使测试类的一个属性存在,var dumping the$class
也会显示 true,因为它是一个对象。
但是,在类没有属性的情况下,我希望发生这种情况:
$class = new test_class();
var_dump($class->property); // false - property does not exist
var_dump($class->second_property); // false - second_property does not exist
var_dump( (bool) $class); // false
但是,我仍然想$class
成为逻辑测试中instanceof
的test_class
但返回 false。
这是可能吗?如果是这样,我会怎么做?
谢谢,奥兹
编辑:
澄清一下,我已经在使用 __get() 魔术函数了。我想要发生的是,如果test_class
没有属性,那么当var_dump
对它执行 a 时,它返回 false 但 aninstanceof
将返回test_class
。
详细...
我正在创建一个复杂的权限系统。用户获得分配的部分,每个部分都有一组权限。
它将像这样工作:
$user = permissions::get_user(USER_ID_HERE);
// Every property of the $user is a section
var_dump($user->this_section_exists); // true - returns an object
var_dump($user->this_section_doesnt); // false - returns a boolean
如果某个部分存在,则它返回该部分权限的对象。
var_dump($user->this_section_exists); // true
var_dump($user->this_section_exists->this_permission_exists); // true
var_dump($user->this_section_exists->this_permission_doesnt); // false
这是边缘情况:
var_dump($user->this_section_doesnt); // false
var_dump($user->this_section_doesnt->some_permission);
// This should also return false, which it does,
// But it throws a notice: "Trying to get property of non-object"
我希望能够在不修改调用该类的代码的情况下抑制该通知,即没有 @ 来抑制.. 或者能够返回一个没有属性的对象,该对象在逻辑测试中评估为 false。