简体   繁体   中英

Define a property in sub class, then use it in parent class, strange behavour in PHP?

In PHP, I define a property named $table_name in the sub class, then in the parent class, I can use this property:

class A{
public function getTable(){
    return $this->table_name;
}
}

class B extends A{

protected $table_name='admin;

}

Could this be possible in Java or C++? I just wonder if this is a good OOP practice, or it is just doable in PHP as PHP is an interpreting language.

Update: I didn't realized this is possible in PHP until I found a MVC framework uses it!When I was learning Java, I didn't remember anything like this, so I thought it might worth discussing.

One of the main points of OOP is polymorphism and the ability to used derived classes. The idea behind this is that you can have access to base properties (in a base class) and rely on them being there in any derived class.

Doing what has been demonstrated above breaks that. It essentially means that base class is useless for anything other than it's derived class and this behaviour should be avoided.

So: You access base properties from derived classes, not the other way around.

Short version: This is bad OOP practice.

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