【问题标题】:Calling instance method from a static method of the same class - safe or not?从同一类的静态方法调用实例方法 - 安全与否?
【发布时间】:2020-10-09 11:25:03
【问题描述】:

我有点疑惑下面的 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 文档,但无法真正找到明确的答案。

谢谢。

【问题讨论】:

  • 私有方法只能由其类成员使用,并且可以在不创建类实例的情况下调用静态方法,因此一切正常。
  • 这是一种不好的做法。访问修饰符用于为类方法和成员提供访问权限。 Private 应该在类中使用,如果您需要任何功能或将来可能需要,那么应该给它 public 访问修饰符。 :)

标签: php


【解决方案1】:

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

私有menas,这个属性只能在这个类内部使用。它不需要在这个对象上下文中。

你的$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 2011-11-10
    相关资源
    最近更新 更多