When I try to Override the class variable same 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
In function overriding, both parent and child classes should have same function name with and number of arguments. It is used to replace parent method in child class. The purpose of overriding is to change the behavior of parent class method. The two methods with the same name and same parameter is called overriding.
In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used.
Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With