PHP OOP: Scope of Properties/Methods
Please advise what's going on here?
We have the following classes working together:
- An abstract base class 'form element'
- An abstract 'container' class that extends the form element class and groups form elements
- A 'field' class that extends the container
In the 'field' class we call a method from the 'form element' class named 'setErrors($vars)' that sets a property named 'hasErrors'. $vars carries a boolean.
There is another method named 'hasErrors()' in the 'form element' class that we try to call in the 'field' class to test the result of the boolean previously set however it returns false.
The hasErrors property that is initially declared as false is not being overwritten?
Form Element Class(Base)
private $hasErrors = false;
public function setErrors($flag)
{
...
$this->hasErrors = $flag;
...
}
public function hasErrors()
{
return $this->hasErrors;
}
Field Class
开发者_Go百科public function validate($value)
{
...
$this->setErrors($foundErrors);//$foundErrors only local to this method
...
}
public function getField()
{
...
if($this->hasErrors())
{
//do something...
}
...
}
Why is the property 'hasErrors' not being overwritten? Would this have something to with the scope of inheritance between the different classes?
Not sure how this works but thanks in advance.
you must declare $hasErrors
as protected property not private.
private methods are not inherited.
I'm sorry to not answer your question directly, but the other answers are misleading and feel I have to step in a bit. Especially since similar test code works fine.
Have you tried stripping your code down to the basics? Just as a test, I created the following which works fine:
<?php
class test {
private $var = 'unset';
public function setVar($val) {
$this->var = $val;
}
public function getVar() {
return $this->var;
}
}
class another extends test {
public function __construct() {
echo $this->getVar() . "\n";
$this->setVar('set');
echo $this->getVar() . "\n";
}
}
class third extends another {
public function __construct() {
parent::__construct(); // This will output 'unset\nset\n'
$this->setVar('set second');
echo $this->getVar() . "\n";
}
}
$a = new third();
Output:
> php tmp.php
unset
set
set second
Updated as per comment, same output:
class another extends test {
public function methodAnother() {
echo $this->getVar() . "\n";
$this->setVar('set');
echo $this->getVar() . "\n";
}
}
class third extends another {
public function methodThird() {
$this->setVar('set second');
echo $this->getVar() . "\n";
}
}
$a = new third();
$a->methodAnother();
$a->methodThird();
精彩评论