从另一个类中的静态函数调用时,PHP 类构造函数未运行 [英] PHP Class constructor not running when called from static function in another class

查看:53
本文介绍了从另一个类中的静态函数调用时,PHP 类构造函数未运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前被盖章,我看不出我哪里做错了.我在下面有一个静态函数 request():

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');

   }

它调用一个静态函数 get(),后者又调用一个私有函数 clean(),它使用在加载注入类的类构造函数中设置的变量消毒

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.

致命错误:在非对象上调用成员函数 filter()

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

此过滤器函数是从注入到构造函数中的 Sanitize 类加载的.

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

谢谢

推荐答案

您说得对,静态调用类时不会调用 __construct().在调用该方法之前,您需要通过某种设置方法注入该 Sanitize 类来手动设置该对象.

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.

例如:

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

那么:

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

这篇关于从另一个类中的静态函数调用时,PHP 类构造函数未运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆