PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
[color=#0000FF]abstract class[/color] MyAbstract {
[color=#0000FF]private [/color]MyProperty;
}
[color=#0000FF]class [/color]MyClass [color=#0000FF]extends [/color]MyAbstract {
[color=#0000FF]function [/color]MyFnc() {
[color=#0000FF]echo [/color]$this->MyProperty; // this does what expected
[color=#FF0000] $this->MyProperty = 1; // why is this allowed? what does this cause to the instance?[/color]
[color=#0000FF]echo [/color]$this->MyProperty; // prints out 1
}
}
$this->MyProperty = 1; // why is this allowed? what does this cause to the instance?
Basically its calling to the MyProperty variable located in the parent class "MyAbstract" and setting that variable to 1;
the "$this" is stating that the variable is inside this class and because "MyClass" extends "MyAbstract" you are able to use and modify and function or variable inside the parent class "MyAbstract".
mischievous wrote:Basically its calling to the MyProperty variable located in the parent class "MyAbstract" and setting that variable to 1;
the "$this" is stating that the variable is inside this class and because "MyClass" extends "MyAbstract" you are able to use and modify and function or variable inside the parent class "MyAbstract".
Almost. That private modifier means that MyClass can't access it.
abstract class MyAbstract {
private $MyProperty;
}
class MyClass extends MyAbstract {
function MyFnc() {
echo $this->MyProperty; // this does what expected
$this->MyProperty = 1; // why is this allowed? what does this cause to the instance?
echo $this->MyProperty; // prints out 1
}
}
$c = new MyClass();
$c->MyFnc();
$this->MyProperty = 1; // why is this allowed? what does this cause to the instance?
It's allowed becouse in php you don't need to define a property before you use it.
If you use a property that does not exist, php creates it for you. So when you do this:
$this->MyProperty = 1;
php creates a property with that name and sets its value to 1. It does not change the value ot MyProperty in the parent.