gist: 543 Download_button fork
public
Public Clone URL: git://gist.github.com/543.git
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?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";
 
?>
 

Owner

Anonymous

Forks

gist: 545 by kastner   Joe's meta-programing for t...

Revisions

  • 123615 Mon Jul 21 17:59:37 -0700 2008