note 100615 deleted from language.oop5.abstract by danbrown
| From: | danbrown@php.net | Date: | Wed, 27 Oct 2010 04:10:06 +0000 |
| Subject: | note 100615 deleted from language.oop5.abstract by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-173490@lists.php.net to get a copy of this message | ||
Note Submitter: grayda [at] at solidinc dot dot org
----
While working on some wrapper functions, I was using code similar to this:
<?php
abstract class Dog {
abstract public function bark();
}
class Chihuahua extends Dog {
public function bark($yip) {
if($yip == true) { echo "YIP YIP YIP YIP"; }
}
}
$c = new Chihuahua;
$c->bark(true);
?>
But kept on getting the error:
Fatal error: Declaration of Chihuahua::bark() must be compatible with that of Dog::bark() in
C:\xampplite\htdocs\base\index.php on line 23
due to Dog::bark NOT having $yip, but Chihuahua::bark having the extra parameter.
My solution was to make all of my function parameters, optional. For example:
<?php
abstract class Dog {
abstract public function bark();
}
class Chihuahua extends Dog {
public function bark($yip = false) {
if($yip == true) { echo "YIP YIP YIP YIP"; } else { echo "WOOF"; }
}
}
?>
By making the "yip" parameter on Chihuahua::bark default to "false", I can have
additional parameters in my function declaration without errors.