PHP可以在类的非静态方法调用的外部静态方法中设置类属性,如果可以,如何设置


php can i set a class property in an external static method called by a non-static method of the class, and if so how?

我有一个类方法,它从一个单独的类调用一个静态方法。有没有一种方法,静态方法可以设置一个公共属性的类调用它?下面是一个基本的例子:

<?php
class MyClass {
    public $status;
    public function before() {
        Helper::setStatus();
    }
    public function after() {
        echo $this->status;
    }
}
class Helper {
    public static function setStatus() {
        parent()->status = "new";
    }
}
$myclass = new MyClass();
$myclass->before();
$myclass->after(); //would hopefully echo "new"

parent()方法只是一个占位符,无论你实际做什么;我知道MyClass不是Helper的父结点。

这可能吗?我是不是用了错误的方法来讨论这个问题?

您需要将类的实例传递给静态方法。在方法内部可以是$this

的例子:

class MyClass {
    public $status;
    public function before() {
        Helper::setStatus($this);
    }
    public function after() {
        echo $this->status;
    }
}
class Helper {
    public static function setStatus($instance) {
        $instance->status = "new";
    }
}
$myclass = new MyClass();
$myclass->before();
$myclass->after(); //would hopefully echo "new"
//you could also set the status from outside by calling the static method
//and passing in your instance.
Helper::setStatus($myclass); //same as calling before.

演示:http://codepad.viper - 7. - com/zw2etr

您可以将MyClass的实例传递给$this可以访问的Helper类

注意:如果你传递任何类方法的实例,它将传入Call By Reference违约。

现场演示