简体   繁体   中英

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

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM