简体   繁体   English

如何测试变量是受保护的还是私有的?

[英]How can I test to see if a variable is protected or private?

I want to write a test to make sure that a variable is protected. 我想编写一个测试来确保变量受到保护。 Is that possible? 那可能吗? Here's what I got. 这就是我得到的。

/**
 * @expectedException       Fatal error
 * @expectedExceptionMessage Cannot access protected property
 */

public function testCannotAccessProtectedProperty() {
    $this->assertEquals($this->object->variableiwanttotest[0], $value);
}

Here is the error message 这是错误消息

PHP Fatal error:  Cannot access protected property Object::variableiwanttotest in /Users/confidential/ObjectTest.php on line 25

This would probably be a good use of reflection. 这可能是反射的好用法。

http://php.net/manual/en/reflectionclass.getproperties.php http://php.net/manual/en/reflectionclass.getproperties.php

By using the filter, you can retrieve the protected property and check for it's existence. 通过使用过滤器,您可以检索受保护的属性并检查其是否存在。

Should be fairly simple to do. 做起来应该很简单。

$prop = new ReflectionProperty(get_class($object), 'propname'));
$this->assertTrue($prop->isProtected());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 设置为默认类型时如何测试私有/受保护的 class 变量 - how to test private / protected class variable when set to default type 为什么我的本地 PHP 函数看不到 $test 变量,如何获取它的值? - Why can't my local PHP function see the $test variable, and how can I get its value? 如何处理/查看php gnupg中的私钥? - How can I handle/see Private Keys in php gnupg? 扩展受保护的类变量并将其标记为私有后,为什么会得到“必须保护或弱于访问级别”的提示? - Why do I get an “Access Level must be protected or weaker” after extending a protected class variable and marking it private? 如何使用PHPUnit测试方法是否私有 - How can I test that a method is private using PHPUnit 如果子类继承了受保护的方法,为什么我不能从私有方法访问受保护的方法? - why can't I access a protected method from a private method if the protected ones are inherited by the subclasses? 如何查看Selenium测试变量中的内容 - How to see what is in a Selenium test variable 我怎样才能使函数看到它外面的变量 - how can i make a function see a variable outside it 如何使用JQuery从表单中看到$ _POST变量? - How can I see $_POST variable from a form using JQuery? 如何查看另一个php文件中定义的变量? - How can I see a variable defined in another php-file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM