PHP Class constructor not running when called from static function in another class

别说谁变了你拦得住时间么 提交于 2019-12-11 19:24:03

问题


I am currently stamped and i can't see where I have done it wrong. I have a static function request() below:

private static function request(){

   if($_SERVER['REQUEST_METHOD']=='GET'){

       $data = RunData::get('cmd');

   }

which calls a static function get() which in turn calls a private function clean() which uses variables set in the class constructor loading an Injected class Sanitize

class RunData {

    public static $sanitize;

    public function __construct( Sanitize $sanitize ){

        self::$sanitize = $sanitize;

    }

   private static function clean($variable_array){    

        if(is_array($variable_array)){

            $filters = array('string' => 'sanitize_string');

            return self::$sanitize->filter($variable_array, $filters);   

        }
    }

    public static function get($variable){

        if(self::clean($_GET)){

            return $_GET[$variable];

        }

    }


}

but when I run I get this error.

Fatal error: Call to a member function filter() on a non-object

This filter function is loaded from the Sanitize Class which is injected into the constructor.

What possibly have I missed??? The constructor doesn't seem to be running

Thanks


回答1:


You're correct, __construct() is not called when the class is invoked statically. You'll need to set up the object manually by injecting that Sanitize class via some sort of setup method before calling the method.

For example:

public static function setSanitizeClass(Sanitize $sanitise)
{
    self::$sanitize = $sanitize;
}

Then:

RunData::setSanitizeClass(new Sanitize());
$data = RunData::get('cmd');


来源:https://stackoverflow.com/questions/28993749/php-class-constructor-not-running-when-called-from-static-function-in-another-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!