开发者

PHP Variable Overriding

When I try to Override the class variable sam开发者_如何学Pythone way as override the class method in PHP. Like:

class DataMapper {
     protected $_name = null;

     public function printName() {
          echo $this->_name;
     }
}

class Model extends DataMapper {
     protected $_name = 'Ana';
}

$test = new Model();
$test->printName();

It's print 'Ana'.

Why PHP can do such a thing like that ? It break the law of object oriented paradigm


It's not. That's how PHP is supposed to work. Have a look at PHP Classes and Objects Visibility.

Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.

Because Model extends DataMapper, it has access to its functions, variables and such but it can override them which is what happened. Although your function lives in the DataMapper class, it's called from (and inherited by) the Model class in which the name is set to Ana.


I think you're just having trouble understanding what $this does. When you reference $this, it is actually referencing the current object.

When you inherit the DataMapper class, the printName() method is made accessible inside Model objects, but the $this reference still refers to the current Model object, $test.

Since the $_name property of Model objects is instantiated to "Ana" it is printing Ana. This is exactly what is expected. Perhaps having another read through the theories of Inheritance and Scope would help you out with understanding what's going on here.


I dont think this breaks the "law of OO". You have inherited the DataMapper class. And thus you have inherited the public function printName(). So when you call the function it acts like the function that belongs to the model class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜