PHP OO: Calling methods on abstract classes?
Please could someone help with the following?
We have the following classes:
- abstract class Element{}
- abstract class Container extends Element{}
- abstract class Field extends C开发者_JS百科ontainer{}
The 'Element' base class has the following properties and methods:
//Element class
private $errors = array();
public function __construct()
{
}
public function setError($error)
{
$this->errors[] = $error;
}
public function getErrors()
{
return "<li>".implode("</li>\n",$this->errors);
}
The 'Container' just groups the elements (objects).
The 'Field' class calls the 'setError' method of the base class and passes a value like this:
//Field class
$this->setError("foo");
For some reason the 'errors' property in the base class doesn't get the value added to it and Im guess its something to do with how the object is instantiated because obviously the abstract classes are not instantiated by default.
The only instantiation of the field is in its inherited form which is:
Text extends Field{}
$field = new Text(etc, etc)
How would you get about resolving this?
Works for me : http://codepad.viper-7.com/Ool7zn
<?php
abstract class Element
{
protected $errors = array();
public function setError($error)
{
$this->errors[] = $error;
}
public function getErrors()
{
return "<li>".implode("</li>\n",$this->errors);
}
}
abstract class Container extends Element{}
abstract class Field extends Container{}
class Text extends Field{}
$t = new Text;
$t->setError('foobar');
echo $t->getErrors();
?>
You're going to have to set the $errors member variable to protected in class Element.
//Element class
protected $errors = array();
Right now, when you call the inherited setError() function on the Text class instance, the Text class instance does not have its own $errors array, so PHP does you the 'favor' of creating one on the fly within the instance of the Text class. However, this is a different $errors member variable from the one in the Elements base class.
Setting the $errors member variable to 'protected' allows the instance of the Text class to interact with the variable in the Element base class, so that PHP does not do you the 'favor' of creating a new $error member (belonging only to the Text class) on the fly.
精彩评论