Stanley Ngumo
Stanley Ngumo

Reputation: 4249

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

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

Upvotes: 0

Views: 4161

Answers (1)

Dan Smith
Dan Smith

Reputation: 5685

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

Upvotes: 1

Related Questions