captinmajid captinmajid - 1 month ago 7
PHP Question

Is die function accept only strings?

this code works:

if (isset($db->error)) {
echo $db->error;
}


This code in not working:

if (isset($db->error)) {
die($db->error);
}


This is my DB class:

class Db {

private $db,
$error;


public function __construct() {
return $this->db = new mysqli(DB_SERVER, DB_USER, DB_PASS, D_NAME);
if ($this->db->connect_error) {
$this->error = $this->db->connect_error;
}
}

}


"D_NAME" is wrong so an error appears but I didn't kill the page, content still appear after the error. Why? Thanks!

Answer

The if block in the constructor is never executed, because you are returning $this->db:

public function __construct() {
        return $this->db = new mysqli(DB_SERVER, DB_USER, DB_PASS, D_NAME);
        // the lines after return will never be executed!
}

This is the first reason why the $db->error is unset.

The second reason is that the $error member is private, which means that you are not allowed to access this property directly. So you should whether make it public, or implement the __get and __isset magic methods.

Using public $error

class Db {
  private $db;
  public $error;

  public function __construct() {
    $this->db = new mysqli('localhost', 'sss3', 'a4J1uQzQCasD', 's3_small');
    if ($this->db->connect_error) {
      $this->error = $this->db->connect_error;
    }
    return $this->db;
  }

}

$db = new Db;
if (isset($db->error)) {
  die($db->error);
}

echo 'xxx', PHP_EOL;

Using __isset and __get magic methods

class Db {
  private $db;
  private $error;

  public function __construct() {
    $this->db = new mysqli('localhost', 'sss3', 'a4J1uQzQCasD', 's3_small');
    if ($this->db->connect_error) {
      $this->error = $this->db->connect_error;
    }
    return $this->db;
  }

  public function __get($key) {
    if ($key === 'error') {
      return $this->error;
    }
  }

  public function __isset($key) {
    if ($key === 'error') {
      return isset($this->error);
    }
  }

}

$db = new Db;
if (isset($db->error)) {
  die($db->error);
}

echo 'xxx', PHP_EOL;