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

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画