phpoopinheritanceobject-oriented-analysis

Is there a way to access a variable from a acctual CHILD class?


ps: I dont want to acess a parent class var but rather an actual child class

How do I access the $table var from User class? I know it sounds silly but is there a way to access this child class var without declaring it in the Model class?

example if I comment public $table in Model class the code wont work anymore because this var "does not exist"

My point being: since this var is going to be "replaced" so why we suppose to declare it?

Thanks

class User extends Model {
    public $table = "User table";    
}
$user = new User();
$user->insertIntoDatabase();

class Model {  
public $table;

  public function insertIntoDatabase() {
  echo "Inserted into ". $this->table ." database <br>";
}
}
?>

Solution

  • "if I comment public $table in Model class the code wont work anymore"

    This is not true -- the child class will still work just fine, because the child can declare attributes that aren't in the parent. The parent won't work, but it's not supposed to, because the parent shouldn't have a table defined. You probably want to define the parent class as an abstract.

    If you want to ensure that a table name is defined in the children but not the parent, then you might avoid using an attribute, and instead use a method. Declare that method as abstract in the parent, then there's no table in the parent, but all children must have one:

    abstract class Model {
    
      // This defines the contract that the child must implement.
      abstract public function getTable(): string;
    
      // This method is available to all children.
      public function insertIntoDatabase() {
        echo "inserting into " . $this->getTable() . "\n";
      }
    }
    
    class User extends Model {
      // This implements the abstract's requirement.
      public function getTable(): string {
        return 'user';
      }
    }
    
    // This generates an error because you can't instantiate an abstract.
    $model = new Model();
    
    // This generates an error because it doesn't define the required getTable() method.
    class Order extends Model {
    }