PHP允許多態代碼在其他語言中產生編譯錯誤。一個簡單的例證說明第一C++代碼,其產生預期編譯錯誤:
class Base {};
class CommonDerivedBase {
public:
// The "= 0" makes the method and class abstract
// virtual means polymorphic method
virtual whoami() = 0;
};
class DerivedBase : public CommonDerivedBase {
public:
void whoami() { cout << "I am DerivedBase \n"; }
};
class Derived1 : public CommonDerivedBase {
public:
void whoami() { cout << "I am Derived1\n"; }
};
class Derived2 : public CommonDerivedBase {
public:
void whoami() { cout << "I am Derived2\n"; }
};
/* This will not compile */
void test_error(Base& db)
{
db.whoami();
}
C++編譯器將發出此錯誤消息爲線db.whoami()
error: no member named 'whoami' in 'Base'
因爲基地沒有一個方法叫做WHOAMI()。但是,類似的PHP代碼在運行時纔會發現這樣的錯誤。
class Base {}
abstract class DerivedCommonBase {
abstract function whoami();
}
class Derived1 extends DerivedCommonBase {
public function whoami() { echo "I am Derived1\n"; }
}
class Derived2 extends DerivedCommonBase {
public function whoami() { echo "I am Derived2\n"; }
}
/* In PHP, test(Base $b) does not give a runtime error, as long as the object
* passed at run time derives from Base and implements whoami().
*/
function test(Base $b)
{
$b->whoami();
}
$b = new Base();
$d1 = new Derived1();
$d2 = new Derived2();
$a = array();
$a[] = $d1;
$a[] = $d2;
foreach($a as $x) {
echo test($x);
}
test($d1);
test($d2);
test($b); //<-- A run time error will result.
foreach循環的工作原理與輸出
I am Derived1
I am Derived2
直到你調用測試($ B),並通過基地的一個實例,將您得到一個運行時錯誤。所以的foreach後,輸出將是
I am Derived1
I am Derived2
PHP Fatal error: Call to undefined method Base::whoami() in
home/kurt/public_html/spl/observer/test.php on line 22
關於你可以做,使PHP的安全將是增加一個運行時檢查 測試如果$ b是類的一個實例的唯一的事情你打算。
function test(Base $b)
{
if ($b instanceof DerivedCommonBase) {
$b->whoami();
}
}
但多態性的要點是消除這種運行時間檢查。 「
」PHP支持多態,但有一些限制。「田田。 :) – 2009-04-15 01:10:36
謝謝:) upvoted你的答案。 – 2009-04-15 09:43:08
爲什麼這個問題的語言不可知?似乎完全是關於PHP的。 – beldaz 2011-01-09 22:38:08