Drew Drew - 1 month ago 15
PHP Question

php class $this->regex not working

I am having an issue inside my class where the

static private
variable is being used inside a function does not work. But it does work when the regex is directly inside it.

class Object{
static private $regex = "/\w+|\-\d+/";

//does not work (NULL)
public function tokenize($text){
preg_match_all($this->regex, $text, $matches);
var_dump($matches);
}

//works
public function tokenize($text){
$regex = "/\w+|\-\d+/";
preg_match_all($regex, $text, $matches);
var_dump($matches);
}
}

$o = New Object;
$o->tokenize("test text -123");

Answer

As of the docs:

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).

To access the private static property from non-static context within your class as you are trying to do this right now, you should access it with

self::$regex

Or you could redeclare your $regex property to be only private (non-static) and then you will be able to access it as $this->regex

Comments