azz0r
azz0r

Reputation: 3311

Extending a class and access constants from the child class

I'm battling with PHP Class inheritance and scope issues. Basically I have a baseclass with a bunch of useful methods (create, save, load) which the devs currently pass a table_name to . I would like to create a bunch of model classes which are empty but extend & inherit the baseclass and can have methods of the same name that get called instead of the baseclass version.

The code below im struggling to get the table_name in a static method from the model class, any advice?

class Model_Baseclass {
    private $table_name;
    public static function create($fields) {
        $table_name = //self::table_name - parent::table_name - const $table_name
        if ($table_name == NULL) {
            throw new exception('You must specify a table.');
        }
    }
}

class Model_Content_Gallery extends Model_Baseclass {
    public $table_name = 'Content_Gallery';
}

$old = Model_Baseclass::create(array('table_name' => 'Content_Gallery'));
$new = Model_Content_Gallery::create(array());

Upvotes: 2

Views: 1451

Answers (2)

JRL
JRL

Reputation: 78003

You need to either make your create method non-static, or your table_name variable static.

If it's required for you to have certain methods static, then starting with php 5.3 you can use late static binding to reference a called class in the context of static inheritance.

Upvotes: 0

acanimal
acanimal

Reputation: 5020

Take a look to some PHP OOP tutorials.

There is no one way to make things. Next is one. For example, in Java is common to create a get/set method for each attribute. This way you can access it from any subclass without using the protected keyword and gaining in clarity.

  • Create a getTableName() method on the parent class.
  • On the instances of the subclass you can call the $this->getTableName() method because it is inherited from the base class.

If you have a MyMethod() on the parent class and want to implement it in the subclass but in a different way, simply create the MyMethod() in the subclass and using the getTableName() can get the table name attribute.

If you subclass.MyMethod() implementation needs to call the parent.MyMethod() then use the parent::MyMehtod() (http://www.php.net/manual/en/keyword.parent.php)

Upvotes: 1

Related Questions