1 回答

TA貢獻1864條經驗 獲得超6個贊
PHP手冊指出:
筆記:
覆蓋父方法時,子方法必須匹配父方法的任何返回類型聲明。如果父方法沒有定義返回類型,那么子方法可能會這樣做。
請注意以下行:“如果父方法未定義返回類型,則子方法可能會這樣做”
所以如果你看看你的例子;Foo 類中的父方法沒有定義返回類型,因此 Bar 類中的子方法可以設置它希望的任何返回類型。
A:
class Foo
{
? ? public function fooMethod()
? ? {
? ? ? ? return []; // returns an array. Type expected: any.
? ? }
}
class Bar extends Foo
{
? ? public function fooMethod(): array
? ? {
? ? ? ? return ['something']; // returns an array, type expected: array
? ? }
}
乙:
這個很好用,因為沒有預先存在的類型期望,所以當子類設置一個類型時,它不會覆蓋任何東西。
class Foo
{
? ? public function fooMethod()
? ? {
? ? ? ? return []; // returns an array, type expected any
? ? }
}
class Bar extends Foo
{
? ? public function fooMethod(): string
? ? {
? ? ? ? return "horses"; // returns a string, type expected: string
? ? }
}
C:
這會導致問題(即你邪惡的軍事月球基地將隨著失去所有的手而被摧毀)因為孩子試圖覆蓋父方法的已經定義的返回類型屬性。
class Foo
{
? ? public function fooMethod(): int
? ? {
? ? ? ? return 874; // returns an int, type expected is int.
? ? }
}
class Bar extends Foo
{
? ? public function fooMethod(): array
? ? {
? ? ? ? return ['something']; // returns an array, type expected int
? ? }
}
- 1 回答
- 0 關注
- 119 瀏覽
添加回答
舉報