开发者

PHP OO: Overriding properties of abstract class

开发者 https://www.devze.com 2023-03-01 03:23 出处:网络
Please could someone advise? We have an abstract base class with a few properties and some methods. The methods(with parameters) are being called from inherited classes with the common intention of

Please could someone advise?

We have an abstract base class with a few properties and some methods.

The methods(with parameters) are being called from inherited classes with the common intention of setting the passed parameters to the properties of the base class except they don't appear to override the default value.

If I set a value(for testing purposes) in the constructor of the abstract(base) class it works fine and anything else passed to the constructor works but what we want to do is get the setErrors method to actually set the value of the property.

Example:

//abstract base class

private $errors = array();//the property we want to overide

public function __construct()
{
$this->errors[] = "This is a required field";//for testing purposes only this works
}

public function setErrors($error)
{
var_dump($error);//this proves that $error is passing something...
$this->errors[] = $error;//this doesnt work(override the property)
var_dump($this->error);//the property now has the $error value...
}

public function getErrors()
{
return "<li>".implode("</li>\n",$this->errors);
}

I'm not sure if this is something to do with the base class being abstract i.e. as it doesnt get instantiated. Please could someone explain why this doesn't work? Thanks in advance for taking an interest.

Edit WE ARE NOT TRYING TO INHERIT THE PRIVATE PROPERTY FROM 开发者_高级运维THE BASE CLASS

What we want to do is override the property with the set method and then use a public get method to return the property.


You're declaring the errors field as private so only the class where it's declared (the abstract superclass) has access to it.

You can either make it protected so subclasses can access it or implement the setErrors method in the superclass.


You should declare $errors as protected instead of private. Read more about Class and Objects visibility ;-)

Update:

Ok, maybe I understand your problem now :P

Try to modify your setErrors like so:

    public function setErrors($error)
    {
        var_dump($error);//this proves that $error is passing something...
        $this->errors = (array) $error;//this works (override the property)
    }


private members are not visible in inherited classes. To do this you must change the visibility to protected.


I find something that may help you. Am not claiming as answer :-(

http://www.triconsole.com/php/oop.php

http://www.killerphp.com/tutorials/object-oriented-php/php-objects-page-4.php


what is basically happening is that php will add the new error to the present error array. eg.

$this->error[0]="this fie..." //default value
$this->error[1]=`$error       //the actual set error
0

精彩评论

暂无评论...
验证码 换一张
取 消