【问题标题】: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 我可以在类的非静态方法调用的外部静态方法中设置类属性,如果可以,如何设置?
【发布时间】:2014-05-06 20:13:40
【问题描述】:

我有一个类方法,它从一个单独的类中调用一个静态方法。有没有办法让静态方法设置调用它的类的公共属性?这是一个基本的例子:

<?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 的父级。

这可能吗?我可能是用错误的方法来解决这个问题吗?

感谢阅读。

【问题讨论】:

    标签: php class inheritance properties static


    【解决方案1】:

    您需要将类的实例传递给静态方法。方法中的哪个可能只是$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

    【讨论】:

    • 多伊!惊人的。谢谢。
    【解决方案2】:

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

    注意:如果你传递任何类的实例意味着,它会传入 Call By Reference 默认。

    Live demo

    【讨论】:

      猜你喜欢
      • 2014-09-27
      • 2015-11-13
      • 1970-01-01
      • 2017-09-18
      • 2012-10-04
      • 1970-01-01
      • 2016-01-27
      • 2016-06-26
      • 1970-01-01
      相关资源
      最近更新 更多