在类内部打印PHP错误

时间:2016-06-24 13:15:34

标签: php class oop

我正在尝试上课而不理解它是如何工作的。有些人解释了如何在函数之间传递变量。我现在的问题是错误。以及如何从类中提取错误并打印到屏幕上。我的输出仅为username。如何获得错误?

class form
{
    protected $username;
    protected $password;
    protected $errors = array();

function __construct($username, $password){
    $this->username = $username;
    $this->password = $password;
}
public function get_errors()
{
    return $this->errors;
}

public function getPassword(){
    return $this->password;
}  

public function getUserName() {
    return $this->username;
    return $this->errors = "No MySQL connection.";
}

}

$test = new form('name1', 'passw2');
echo $test->getUserName();

3 个答案:

答案 0 :(得分:1)

你不能在函数内返回两次。但是你可以在下面实现你想要的东西: -

public function getUserName() {
    $this->errors = "No MySQL connection.";
    return $this->username.'<br/>'.$this->errors;
}

注意: - 这是解决方案,但您的代码没有意义。你必须做一些有用的东西

答案 1 :(得分:1)

尝试抛出异常

public function getUserName() {
   if($this->errors) {
     throw new Exception($this->errors);
   }
   return $this->username;
}

$test = new form('name1', 'passw2');

try {
  echo $test->getUserName();
} catch(Exception $error) {
  echo 'Error:'.$error->getMessage();
}

如果您收到错误,可以轻松捕获此错误并输出到webconsoleerror log;

答案 2 :(得分:1)

class form
{
    protected $username;
    protected $password;
    protected $errors = array();

    function __construct($username, $password){
        $this->username = $username;
        $this->password = $password;
    }
    public function getErrors()
    {
        return $this->errors;
    }

    public function getPassword()
    {
        return $this->password;
    }  

    public function getUserName()
    {
        /* Add some an error to an error's array */
        $this->errors[] = "No MySQL connection.";
        return $this->username;
    }
}

$test = new form('name1', 'passw2');
echo $test->getUserName();
var_dump($test->getErrors()); /* Get errors from a class */