CroStorm99 CroStorm99 - 6 months ago 25
PHP Question

OOP PHP call to a member function on null

I am getting this error


Fatal error: Call to a member function passed() on null


but can't find mistake, I already looked at other posts and didn't find useful.

So I have 2 files, first register.php

<?php

require_once 'core/init.php';

if(Input::exists()){
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_again' => array(
'required' => true,
'matches' => 'password'
),
'name' => array(
'required' => true,
'min' => 3,
'max' => 50
)
));

if($validation->passed()){
echo 'Passed';
}else{
print_r($this->errors());
}
}


?>

and second Validate.php


class Validate{

private $_passed = false,
$_errors = array(),
$_db = null;

public function __construct(){
$this->_db = DB::getInstance();
}

public function check($source, $items = array()){
foreach($items as $item => $rules){
foreach($rules as $rule => $rule_value){

$value = $source[$item];

if($rule === 'required' && empty($value)){
$this->addError("{$item} is required");
}else{

}
}
}

if(empty($this->_errors)){
$this->_passed = true;
}
}

private function addError($error){
$this->_errors[] = $error;
}

public function errors(){
$this->_errors;
}

public function passed(){
return $this->_passed;
}

}


It shows me error in first file in
if($validation->passed()){


thanks for help

Answer

You function $validate->check doesn't return anything, so your $validation stays null. When you then call $validation->passed(), $validation is still null. Thats why the error says

Fatal error: Call to a member function passed() on null

because you are trying to call function passed on null. What you probably intended to do is:

if(Input::exists()){
    $validate = new Validate();
    $validate->check($_POST, array(
        'username' => array(
            'required' => true,
            'min' => 2,
            'max' => 20,
            'unique' => 'users'
        ),
        'password' => array(
            'required' => true,
            'min' => 6
        ),
        'password_again' => array(
            'required' => true,
            'matches' => 'password'
        ),
        'name' => array(
            'required' => true,
            'min' => 3,
            'max' => 50
        )
    ));

    if($validate->passed()){
        echo 'Passed';
    }else{
        print_r($validate->errors());
    }
}
Comments