douzhi3105 2015-03-11 17:45
浏览 172
已采纳

从另一个类中的静态函数调用时,PHP类构造函数未运行

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条回答 默认 最新

  • duanqing2209 2015-03-11 17:49
    关注

    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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊