如何让PHP私人类var不是私有的? [英] How come the PHP private class var is not private?

查看:147
本文介绍了如何让PHP私人类var不是私有的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编程,遇到这个问题:
在下面的代码示例中,一个公共函数设置一个专用的varriable。现在人们会期望该私有varriable的内容是私有的,认为$ GLOBALS varriable(一个超全局的)可以访问它,至少读它。为什么?有没有办法处理这个问题?

 <?PHP 
error_reporting(E_ALL);

class test {
private $ test ='';

public function test()
{
$ this-> test ='可以看到我吗?
}
}

$ b = new test();
$ b-> test();

pre($ GLOBALS ['b']);
//结果:
//测试对象
//(
// [test:test:private] =>可以看到我吗?
// )

somefunc();
function somefunc()
{
pre($ GLOBALS ['b']);
//结果:
//测试对象
//(
// [test:test:private] =>可以看到我吗?
// )
}

echo $ b-> test;
//结果:
//致命错误:无法访问私有属性test :: $ test

function pre($ a){
echo'< pre ;';
print_r($ a);
echo'< / pre>';
}
?>

谢谢您,
Jeffrey

print_r 和 var_dump 仍能看到它们。



所以原因是封装,而不是直接隐藏数据


I was programming, and came across this problem: In the code sample below, a public function sets a private varriable. Now one would expect the content of that private varriable is private, thought the $GLOBALS varriable (a superglobal) can access it, and at least read it. why? is there a way to prefent this?

<?PHP
error_reporting( E_ALL );

class test {
    private $test = '';

    public function test()
    {
        $this->test = 'Can u see me?'; 
    }
}

$b = new test();
$b->test();

pre( $GLOBALS['b'] );
// Result:
// test Object
// (
//     [test:test:private] => Can u see me?
// )

somefunc();
function somefunc()
{
    pre( $GLOBALS['b'] );
    // Result:
    // test Object
    // (
    //     [test:test:private] => Can u see me?
    // )
}

echo $b->test;
// Result:
// Fatal error: Cannot access private property test::$test

function pre( $a ) {
    echo '<pre>';
    print_r( $a );
    echo '</pre>';
}
?>

Thank you, Jeffrey

解决方案

private keyword is about preventing the property/method from being accessed outside the class from the programming perspective. The service functions print_r and var_dump still able to see them.

So the reason is encapsulation, not literal hiding the data

这篇关于如何让PHP私人类var不是私有的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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