繁体   English   中英

从同一类的静态方法调用实例方法 - 安全与否?

[英]Calling instance method from a static method of the same class - safe or not?

我对以下 PHP 代码的工作原理感到有些困惑:

class A
{
    private function test()
    {
        print('test' . PHP_EOL);
    }
    
    static public function makeInstanceAndCall()
    {
        $test = new A();
        $test->test();
    }
}

A::makeInstanceAndCall();

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

test() 方法的最后一行调用显然失败了,但为什么从 makeInstanceAndCall() 方法的静态上下文中调用相同的方法似乎没有。

在生产环境中依赖这种行为是否安全?

我可能缺少什么 PHP 功能来完成这项工作。 我刚刚花了一些时间浏览 PHP 文档,但无法真正找到明确的答案。

谢谢。

您在这里缺少的是,在 PHP 中private关键字并不意味着对象的此属性只能由该对象本身使用。

私有的意思是,这个属性只能在这个类中使用。 它不需要在这个对象上下文中。

你的$test->test(); 在类A 内,因此它可以使用它的私有属性;)

看这个例子:

class A
{
    private string $name;
    
    public function __construct($name) {
        $this->name = $name ;
    }
    
    private function sayName()
    {
        print('My name is ' . $this->name);
    }
    
    public function sayAnotherObjectName( self $anotherObject ) {
     $anotherObject->sayName();   
    }
    
}

$John = new A('John');
$Anie = new A('Anie');
$John->sayAnotherObjectName($Anie);

从函数sayAnotherObjectName()您可以调用私有的sayName()函数,即使是在另一个对象的上下文中! 所以,上面代码的输出是: My name is Anie

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM