How to transfer data to the parent class through the child?

For example, in Yii2 there is a class ActiveRecord from which I inherit. I override the tableName method, and return my parameter. It falls into the methods of the parent class. How?

 class Item extends ActiveRecord { public static function tableName() { return 'item'; } } 

1 answer 1

You can refer to the parent class to any methods defined in the heirs. Below Base::printProperty() refers to the property() method, which we override in the heirs. Moreover, we can demand that the heirs define property() declaring it in the base class to be abstract (although this is not at all necessary).

 abstract class Base { public function printProperty() { echo $this->property(); } abstract function property(); } class Child1 extends Base { public function property() { return 'Child1'; } } class Child2 extends Base { public function property() { return 'Child2'; } } $obj1 = new Child1(); echo $obj1->printProperty(); // Child1 $obj2 = new Child2(); echo $obj2->printProperty(); // Child2 

The same is done in ActiveRecord, only the tableName() method is not abstract, but implements the default logic.

 class ActiveRecord extends BaseActiveRecord { ... public static function tableName() { return '{{%' . Inflector::camel2id( StringHelper::basename(get_called_class()), '_') . '}}'; } ... } 
  • Thank you!) What you need) - Arzek
  • And how to do all this using only static methods (it is not necessary to create a class object)? - Arzek
  • one
    @Arzek is the same, just add the static keyword to the function definition. In this case, you will not need objects, and inside functions you will not be able to access $ this-> - cheops