从PHP类的外部调用私有方法和私有属性 [英] Call private methods and private properties from outside a class in PHP

查看:499
本文介绍了从PHP类的外部调用私有方法和私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在非常罕见的特定情况下,我想从类外部访问私有方法和变量.

I want to access private methods and variables from outside the classes in very rare specific cases.

我已经看到,尽管使用了自省,但这是不可能的.

I've seen that this is not be possible although introspection is used.

具体情况是下一个:

我想要这样的东西:

class Console
{
    final public static function run() {

        while (TRUE != FALSE) {
            echo "\n> ";
            $command = trim(fgets(STDIN));

            switch ($command) {
                case 'exit':
                case 'q':
                case 'quit':
                    echo "OK+\n";
                    return;
                default:
                    ob_start();
                    eval($command);
                    $out = ob_get_contents();
                    ob_end_clean();

                    print("Command: $command");
                    print("Output:\n$out");         

                    break;
            }
        }
    }
}

该方法应该能够被注入如下代码中:

This method should be able to be injected in the code like this:

Class Demo
{
    private $a;

    final public function myMethod()
    {
        // some code
        Console::run();
        // some other code
    }

    final public function myPublicMethod()
    {
        return "I can run through eval()";
    }

    private function myPrivateMethod()
    {
        return "I cannot run through eval()";
    }
}

(这只是一个简化.真正的简化是通过一个套接字,并实现了更多的东西……)

(this is just one simplification. the real one goes through a socket, and implement a bunch of more things...)

所以...

如果实例化类Demo并调用$ demo-> myMethod(),您将获得一个控制台:该控制台可以访问第一个方法,编写如下命令:

If you instantiate the class Demo and you call $demo->myMethod(), you'll get a console: that console can access the first method writing a command like:

> $this->myPublicMethod();

但是您不能成功运行第二个:

But you cannot run successfully the second one:

> $this->myPrivateMethod();

您有任何想法吗?或者是否有任何PHP库允许您执行此操作?

Do any of you have any idea, or if there is any library for PHP that allows you to do this?

非常感谢!

推荐答案

只需将方法公开.但是,如果您想变得棘手,可以尝试以下方法(PHP 5.3):

Just make the method public. But if you want to get tricky you can try this (PHP 5.3):

class LockedGate
{
    private function open()
    {
        return 'how did you get in here?!!';
    }
}

$object = new LockedGate();
$reflector = new ReflectionObject($object);
$method = $reflector->getMethod('open');
$method->setAccessible(true);
echo $method->invoke($object);

这篇关于从PHP类的外部调用私有方法和私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆