Thursday 10 March 2016

class - couple of questions about OO and classes in PHP



I am learning about OO and classes, I have a couple of questions about OO and classes in PHP





  1. As I understand it, a class that extends another class simply means that the class that extends the other class has access to the variables/properties and the functions/methods of the class that it is extending from. Is this correct?


  2. I know that a static method or property are basically the same as a procedural function or variable outside of a class and can be used pretty much anywhere. Is this correct?


  3. Public means any class can access it and Private means only the class that is is encapsulated in or a class that is extended from the owner of can access and use. Is this correct?



Answer



1) Yes, that's correct. A child class inherits any protected or public properties and methods of its parent. Anything declared private can not be used.



2) This is true. As long as the class is loaded (this goes well with your autoloading question from before), you can access static methods via the scope resolution operator (::), like this: ClassName::methodName();



3) You have the meaning of public correct, but as I mentioned earlier, private methods can only be used by the class they are declared in.




class parentClass
{
private $x;
public $y;
}

class childClass extends parentClass
{
public function __construct() {

echo $this->x;
}
}

$z = new childClass();


The above code will result in a NOTICE error being triggered, as $x is not accessible by childClass.





Notice: Undefined property:
childClass::$x




If $x was declared protected instead, then childClass would have access. Edit: A property declared as protected is accessible by the class that declares it and by any child classes that extend it, but not to the "outside world" otherwise. It's a nice intermediate between public and private.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...