开发者

How can I call a parent method from the instantiating class?

开发者 https://www.devze.com 2023-02-27 17:05 出处:网络
In my proje开发者_开发百科ct all of my view classes are extensions of a base view class which handles all common aspects to the views, including error messages. In one of the view extensions I am crea

In my proje开发者_开发百科ct all of my view classes are extensions of a base view class which handles all common aspects to the views, including error messages. In one of the view extensions I am creating an instance of another 'helper' class which may need to output error messages.

Is there any way that I can reference my addError method from the parent of the class that created the instance of the helper class, directly from within a method of the helper class itself?

e.g.

class baseview {
    ...
    public function addError($message) {
        ...
    }
    ...
}

class pageview extends baseview {
    ...
    $helper = new helper();
   ...
}

class helper {
    ...
    public function myFunction($var) {
        if( $var ) { ... }
        else { theClassThatInstantiatedMe::addError('Error Message') }
    }
    ...
}

~ OR ~

Could someone please suggest a better way to structure my system to better handle this type of situation?


2 simple solutions are:

Store the parent class in the helper class:

class pageview extends baseview {
    ...
    $helper = new helper($this);
   ...
}

class helper {
    function __construct($parent)
    {
        $this->_parent=$parent;
    }
    ...
    $this->_parent->addError("...");
}

Othwerwise make the addError function public and static so that you can call it in the helper class without store the parent class instance:

class baseview {
    ...
    static public function addError($message) {
        ...
    }
    ...
}

class helper{
     ...
     baseview::addError("...");
}


From your example, I would have supposed that you meant baseview to be used universally, and so "baseview::addError('Error Message');"

But from the text, I gather that there may be differnt classes. In that case, you are going to have to pass a reference to the creating class into the helper, like this:

class pageview extends baseview {
...
$helper = new helper($this);

... }

class helper { protected $creator; ... public function myFunction($creator, $var) {

    $this->creator = $creator;
    if( $var ) { ... }
    else { $creator->addError('Error Message') }
}
...

}


If you want clean code, you should separate wiring (object creation) and logic.

Here is THE pdf all coders should have read at least once: Writing Testable Code

It is a pdf found on Misko Hevery's blog (A google "clean code" evangelist).

If you prefer videos, you can check these: Misko's conferences at Google

0

精彩评论

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