Am I being stupid or does preg_match()
not accept global class variables?
class test{
private$username,$usernameValidation;
public function __construct($username){
$this->username=$username;
$this->usernameValidation="/^[a-zA-Z0-9]{0,8}$/";
}
public function validate(){
if(!preg_match($this->usernameValidation,$this->username)){
//failed;
}
}
}
Every time I compile a function like this, it seems to tell me the the expression is empty. Seems to work as preg_match("/^[a-zA-Z0-9]{0,8}$/",$this->username);
.
You can try keeping regex assignment at class level:
class test {
const UsernameValidation = '/^[a-zA-Z0-9]{0,8}$/';
private $username;
public function __construct($username){
$this->username=$username;
}
public function validate(){
if(!preg_match(UsernameValidation, $this->username)) {
//failed;
}
}
}
{,8}
is not a valid repetition, I guess you want: {0,8}
or {8,}
You need a space between private
and $username
or you will get a syntax error. This code works:
class test{
private $username,$usernameValidation;
public function __construct($username){
$this->username=$username;
$this->usernameValidation="/^[a-zA-Z0-9]{0,8}$/";
}
public function validate(){
if(!preg_match($this->usernameValidation,$this->username)){
echo 'failed';
}
else {
echo 'matched';
}
}
}
$foo = new test('abcdefg');
$foo->validate();