Skip to content

Instantly share code, notes, and snippets.

@wjaspers
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wjaspers/9353164 to your computer and use it in GitHub Desktop.
Save wjaspers/9353164 to your computer and use it in GitHub Desktop.
PHP stdClass reflection bug
<?php
// @link https://bugs.php.net/bug.php?id=66821
class Helper
{
protected $reflector;
protected $object;
public function __construct($object)
{
$this->object = $object;
$this->reflector = new ReflectionClass($object);
}
public function __get($property)
{
$property = $this->reflector->getProperty($property);
$property->setAccessible(true);
return $property->getValue($this->object);
}
}
class TestObj
{
public $publicNullVar = null;
public $publicIntVar = 1;
protected $protectedNullVar = null;
protected $protectedIntVar = 1;
}
$testObj = new TestObj;
$stdObj = new stdClass;
$stdObj->publicNullVar = null;
$stdObj->publicIntVar = 1;
$testHelper = new Helper($testObj);
var_dump($testHelper->publicNullVar);
$stdHelper = new Helper($stdObj);
var_dump($stdHelper->publicNullVar);
@wjaspers
Copy link
Author

wjaspers commented Mar 4, 2014

Output:

NULL
PHP Fatal error:  Uncaught exception 'ReflectionException' with message 'Property publicNullVar does not exist' in /test.php:19
Stack trace:
#0 /test.php(19): ReflectionClass->getProperty('publicNullVar')
#1 /test.php(49): Helper->__get('publicNullVar')
#2 {main}
  thrown in /test.php on line 19

@wjaspers
Copy link
Author

wjaspers commented Mar 4, 2014

Expected Output:

NULL
NULL

@wjaspers
Copy link
Author

wjaspers commented Mar 4, 2014

Welp, I'm a dolt.

PHP has a ReflectionClass AND a ReflectionObject.
The latter works for inspecting objects correctly, and doesn't act strangely with stdClass objects.

Thanks to the PHP community for resolving this issue so quickly!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment