so I'm trying to work out an issue I'm having in designing PHP classes. I've created a base class, and assigned private variables. I have child classes extending this base class, which make reference and changes to these private variables through functions of the base class. Here's an example, keep in mind I'm still confused about the difference between private
and protected
methods/variables (let me know if I'm doing it wrong!):
base.class.php
<?php
class Base {
private $test;
public function __construct(){
require('sub.class.php');
$sub = new Sub;
echo($this->getTest());
}
public function getTest(){
return $this->test;
}
protected function setTest($value){
$this->test = $value;
}
}
?>
sub.class.php
<?php
class Sub extends Base {
public function __construct(){
parent::setTest('hello!');
}
}
?>
So I'd expect the result to be hello!
printed on the screen - instead there is nothing. There could be a fundamental misunderstanding of classes on my part, or maybe I'm just doing something wrong. Any guidance is very much appreciated! Thanks.
EDIT:
Thank you to everyone who contributed an answer - I think, despite the excellent solutions, that child classes are actually not what I need - it seems delegate classes may be more useful at this point, as I don't really need to reference the Base functions from within the other classes.
Inheritance means that an object of the child class automatically includes the object fields and methods defined in the parent class. But, if the inherited fields are private, which they should be, the child class can not directly access the inherited fields using dot notation.
But, if you inherit a class that has private fields, including all other members of the class the private variables are also inherited and available for the subclass. But, you cannot access them directly, if you do so a compile-time error will be generated.
No; since $privattrib is private, Base's version and Derived's version are completely independent.
We can use the private access modifier for class variables and methods but not for PHP class. When a class member - a variable or a function, is declared as private then it cannot be accessed directly using the object of the class. For example: <?
Should be like this:
base.class.php:
class Base {
private $test;
public function __construct() {
echo $this->getTest();
}
public function getTest() {
return $this->test;
}
protected function setTest($value) {
$this->test = $value;
}
}
sub.class.php:
class Sub extends Base {
public function __construct() {
parent::setTest('hello!'); // Or, $this->setTest('hello!');
parent::__construct();
}
}
main code:
require 'base.class.php';
require 'sub.class.php';
$sub = new Sub; // Will print: hello!
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