Page 1 of 1

inherited property behaviour

Posted: Sun Apr 19, 2009 3:24 pm
by ing.tomas.kucera
Hi,
can any one explain me, what exactly does the red coloured line in the code below, please.
Thanks a lot.
Tom

Code: Select all

 
[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
  }
}
 

Re: inherited property behaviour

Posted: Sun Apr 19, 2009 11:05 pm
by mischievous

Code: Select all

$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".

For more info see http://www.spoono.com/php/tutorials/tutorial.php?id=27


Hope that helps!

Re: inherited property behaviour

Posted: Mon Apr 20, 2009 12:00 am
by requinix
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.

Code: Select all

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();

Code: Select all

Notice: Undefined property: MyClass::$MyProperty in ... on line 9
1

Re: inherited property behaviour

Posted: Mon Apr 20, 2009 5:48 am
by Pulni4kiya
$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.

Re: inherited property behaviour

Posted: Wed Apr 22, 2009 9:15 pm
by mischievous
Good to know! haha ... my bad didnt mean to give false information! appreciate it guys!