yan
yan

Reputation: 480

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

Upvotes: 1

Views: 936

Answers (2)

cweiske
cweiske

Reputation: 31107

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

Upvotes: 3

Adam Ritter
Adam Ritter

Reputation: 989

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.

Upvotes: 3

Related Questions