PHP # 通过引用访问类的受保护或私有变量是有意还是错误?

解释

在研究过程中,我创建了下面这个小代码片段,以更好地了解 php。我现在创建这个问题的原因是为了接触更有经验的开发人员,以免过多地阻塞系统,并且不要让系统变得更进一步。


下面是有关如何访问类范围之外的私有或受保护变量的代码示例。


代码示例

此代码示例将设置为对类内部$TestVar私有变量的引用。test::Atest


<?php

class Test {

    private $A = 123;

    

    public function changeA ($Var){

        $this->A = $Var;

    }

    

    public function createReference(){

        return([&$this->A]);

    }

}


$TestClass = new Test();

$TestVar = &$TestClass->createReference()[0];

通过使用Test::changeA()或改变$TestVar的内容test::A可以被改变。


//Test Current Value

var_dump($TestVar);


//Change test::A the intended way

$TestClass->changeA(321);

var_dump($TestVar);


//Change it by reference

$TestVar = 777;

var_dump($TestVar);

var_dump($TestClass);

预期输出:


int 123

int 321

int 777


object(Test)[1]

  private 'A' => int 777

结果

为什么我认为这是一个错误,手册在描述和示例中都指出:

声明为 protected 的成员只能在类本身内部以及通过继承类和父类访问。

声明为私有的成员只能由定义该成员的类访问。

这是不可能的或有意的。

这是一个错误、一个错误的文档还是只是一个必须忍受的错误。


函数式编程
浏览 104回答 1
1回答

烙印99

这种行为是完全正常的。事实上,如果您的属性是对象(始终通过引用传递),您甚至不需要显式创建引用:class Foo{&nbsp; &nbsp; private Datetime $when;&nbsp; &nbsp; public function __construct()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->when = new DateTime('1950-12-31');&nbsp; &nbsp; }&nbsp; &nbsp; public function getWhen(): DateTime&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $this->when;&nbsp; &nbsp; }}$f = new Foo();$w = $f->getWhen();$w->modify('+50 years');var_dump($w, $f);object(DateTime)#2 (3) {&nbsp; ["date"]=>&nbsp; string(26) "2000-12-31 00:00:00.000000"&nbsp; ["timezone_type"]=>&nbsp; int(3)&nbsp; ["timezone"]=>&nbsp; string(13) "Europe/Madrid"}object(Foo)#1 (1) {&nbsp; ["when":"Foo":private]=>&nbsp; object(DateTime)#2 (3) {&nbsp; &nbsp; ["date"]=>&nbsp; &nbsp; string(26) "2000-12-31 00:00:00.000000"&nbsp; &nbsp; ["timezone_type"]=>&nbsp; &nbsp; int(3)&nbsp; &nbsp; ["timezone"]=>&nbsp; &nbsp; string(13) "Europe/Madrid"&nbsp; }}这与您引用的文档并不矛盾。该属性本身无法访问:$f->when;// PHP Fatal error:&nbsp; Uncaught Error: Cannot access private property Foo::$when参考文献是一种不同的语言功能。也许通过另一个例子更容易理解:function a(){&nbsp; &nbsp; $local_variable = 1;&nbsp; &nbsp; b($local_variable);&nbsp; &nbsp; echo "b modified a's local variable: $local_variable\n";}function b(&$number){&nbsp; &nbsp; echo "b can read a's local variable: $number\n";&nbsp; &nbsp; $number++;}a();b can read a's local variable: 1b modified a's local variable: 2
打开App,查看更多内容
随时随地看视频慕课网APP