简体   繁体   中英

PHP - defined constant returns undefined

I'm working on a CodeIgniter project and I've been having some trouble with constants.

My instances model - which extends a generic MY_Model - defines a constant of its corresponding SQL table, 'instances'.

const DB_TABLE = 'instances';

Elsewhere, $instances_model->get_by() is called, which lives in MY_Model, that references that constant, in the context of Instances_model which should override the constant of the same name in MY_Model. get_by() begins with:

if(!defined('$this::DB_TABLE')) exit($this->table_not_set_error);

The application returns "Instances_model error: table name is not set" and exits.


Declaration/constructor of MY_Model:

class MY_Model extends CI_Model {

  const DB_TABLE = 'abstract';

  public $table_not_set_error;

  function __construct() {
    parent::__construct();

    $this->table_not_set_error = get_class($this) . " error: table name is not set.";
  }

get_by:

public function get_by($attribute, $value = null, $include_obsolete=0)
  {
    var_dump(defined('$this::DB_TABLE'));
    var_dump($this::DB_TABLE);
    if(!defined('$this::DB_TABLE')) exit($this->table_not_set_error);

Instances_model:

class Instances_model extends MY_Model
{

  const DB_TABLE = 'instances';

  public function __construct()
  {
    parent::__construct();

The two var_dumps in the get_by() function return false and "instances", respectively. This doesn't make sense. If PHP can return the value of the constant, how can it not be defined? It's even returning the correct context: "instances" instead of "abstract". Why does PHP think $this::DB_TABLE is undefined?

Thanks for your help.

The issue is that you're using $this to access a class constant, which is not an instance constant . You want:

if (!defined('self::DB_TABLE')) exit($this->table_not_set_error);

And:

var_dump(self::DB_TABLE);

You can also use static:: rather than self:: if you want a child class to be able to redefine the constant to its own value. You use $this-> to access things that belong to an instance object of a class but, self:: or static:: to access things that belong to a class itself, like a constant or a static method or property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM