有没有办法从实际的CHILD类访问变量?

问题描述 投票:0回答:1

ps:我不想访问父类var,而是访问实际的子类

如何从 User 类访问 $table var?我知道这听起来很愚蠢,但是有没有办法访问这个子类变量而不在模型类中声明它?

example如果我在模型类中评论public $table,代码将不再工作,因为这个var“不存在”

我的观点是:既然这个变量将被“替换”,那么为什么我们要声明它呢?

谢谢

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>";
}
}
?>
php oop inheritance object-oriented-analysis
1个回答
0
投票

“如果我在模型类中评论 public $table ,代码将不再工作”

这不是真的——子类仍然可以工作得很好,因为子类可以声明父类中没有的属性。 parent 不起作用,但它不应该起作用,因为父级不应该定义表。您可能想将父类定义为抽象类。

如果您想确保在子级而不是父级中定义表名,那么您可以避免使用属性,而是使用方法。在父级中将该方法声明为抽象方法,则父级中没有表,但所有子级都必须有一个:

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 {
}
© www.soinside.com 2019 - 2024. All rights reserved.