我有一个类方法,它从一个单独的类调用静态方法。有没有办法静态方法可以设置调用它的类的公共属性?这是一个基本的例子:
<?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
的父级。
这可能吗?我是否可能采用错误的方法解决这个问题?
感谢阅读。
答案 0 :(得分:2)
您需要将类的实例传递给静态方法。方法内部可能只是$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.
答案 1 :(得分:0)