Skip to content

Instantly share code, notes, and snippets.

@kastner
Forked from anonymous/gist:543
Created July 22, 2008 01:00
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 kastner/545 to your computer and use it in GitHub Desktop.
Save kastner/545 to your computer and use it in GitHub Desktop.
Joe's meta-programing for testing private stuff in PHP
<?php
class Foo
{
protected $user = null;
public function __construct($user)
{
$this->user = $user;
}
protected function test($name)
{
return "Hello $name!\n";
}
}
function getProxy($class, array $args = array())
{
if (!class_exists($class)) {
throw Exception('Class does not exist');
}
$code = <<< CODE
class Proxy_$class extends $class
{
public function __get(\$var)
{
static \$ref = null;
if (is_null(\$ref)) {
\$ref = new ReflectionClass('$class');
}
\$parts = explode('_', \$var);
\$type = array_shift(\$parts);
\$var = implode('_', \$parts);
\$prop = \$ref->getProperty(\$var);
\$func = 'is' . ucfirst(\$type);
if (!\$prop->\$func()) {
throw Exception(\$var . ' is not ' . \$type);
}
return \$this->\$var;
}
public function __call(\$function, array \$args = array())
{
static \$ref = null;
if (is_null(\$ref)) {
\$ref = new ReflectionClass('$class');
}
\$parts = explode('_', \$function);
\$type = array_shift(\$parts);
\$function = implode('_', \$parts);
\$method = \$ref->getMethod(\$function);
\$func = 'is' . ucfirst(\$type);
if (!\$method->\$func()) {
throw Exception(\$function . ' is not ' . \$type);
}
return call_user_func_array(array(\$this, \$function), \$args);
}
}
CODE;
eval($code);
$ref = new ReflectionClass('Proxy_' . $class);
$obj = $ref->newInstanceArgs($args);
return $obj;
}
$obj = getProxy('Foo', array('joestump'));
echo $obj->protected_user . "\n";
echo $obj->protected_test($obj->protected_user) . "\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment