这是我的代码:
文件Application.php:
class Application {
private $upgrade;
public function __construct($upgrade = null) {
if (!is_null($upgrade) && ($upgrade instanceof ApplicationUpgrade)) {
$this->setUpgrade($upgrade);
if ($this->getUpgrade()->getVersion() > $this->getVersion()) {
$this->getUpgrade()->upgrade();
}
}
}
public function getVersion() {
return '1';
}
public function getUpgrade() {
return $this->upgrade;
}
public function setUpgrade(ApplicationUpgrade $upgrade) {
$this->upgrade = $upgrade;
}
public function sayHi($name) {
echo 'Hi ' . $name . '!';
}
}
文件ApplicationUpgrade.php:
class ApplicationUpgrade {
public function getVersion() {
return '1.1';
}
public function upgrade() {
//code upgrade here...
}
public function sayHi($name) {
echo 'Hi ' . $name . ', Method has been upgraded!';
}
}
现在:
$app = new Application(new ApplicationUpgrade());
$app->sayHi('A');
我想在升级之前,说他回归'嗨A!'在升级之后,sayHi返回'嗨A,方法已升级!'。
答案 0 :(得分:0)
你可以这样做,但我认为这有点不好,但无论如何你走了
<?php
class Application {
public function sayHi($name) {
if($this->upgrade !== null) {
$this->upgrade->sayHi($name);
}
else {
echo 'Hi ' . $name . '!';
}
}
}
从类外部覆盖方法或传递参数
是不可能的另一个选项是扩展Application类并覆盖一些方法 http://php.net/manual/en/language.oop5.inheritance.php
你应该阅读文档,因为它是学习OOP基础知识的一个很好的起点
class Application {
public function sayHi() {
echo('hi version1');
}
}
class ApplicationV2 extends Application {
public function sayHi() {
echo('hi version2');
}
}
$app = new ApplicationV2();
$app->sayHi();
此外,我不会这样做来管理不同的版本,你应该google arround以获得更好的解决方案并做一些研究