2016-04-27 116 views
2

我一直在使用5.6,但它有動態類型的真正限制。我剛剛查看了PHP7的文檔,最終看起來他們正在削減困擾舊版本的問題,看起來他們實際上是設計現在的語言。PHP7是否支持多態?

我看到它支持參數類型提示,這是否意味着我們實際上可以具有多態函數?

還有一個問題,切線相關但是PHP7的當前版本是一個穩定版本?

+2

PHP不支持Java中的多態(我懷疑這是你所問的) - 請參閱[本文](http://code.tutsplus.com/tutorials/understanding-and-applying-多態性 - 在PHP中 - 網絡-14362)或[這一個](http://phpenthusiast.com/object-oriented-php-tutorials/polymorphism-in-php),它適用於PHP7儘可能多PHP5 –

+3

自11月以來,PHP7一直保持穩定版本 –

回答

1

關於你對函數參數的類型提示的問題,答案是「是」,PHP在這方面支持多態。

我們可以採用矩形和三角形的典型形狀示例。讓我們先定義這三個類別:

Shape類

class Shape { 
    public function getName() 
    { 
     return "Shape"; 
    } 

    public function getArea() 
    { 
     // To be overridden 
    } 
} 

Rectangle類

class Rectangle extends Shape { 

    private $width; 
    private $length; 

    public function __construct(float $width, float $length) 
    { 
     $this->width = $width; 
     $this->length = $length; 
    } 

    public function getName() 
    { 
     return "Rectangle"; 
    } 


    public function getArea() 
    { 
     return $this->width * $this->length; 
    } 
} 

三角類

class Triangle extends Shape { 

    private $base; 
    private $height; 

    public function __construct(float $base, float $height) 
    { 
     $this->base = $base; 
     $this->height = $height; 
    } 

    public function getName() 
    { 
     return "Triangle"; 
    } 

    public function getArea() 
    { 
     return $this->base * $this->height * 0.5; 
    } 
} 

現在我們可以編寫一個採用上述Shape類的函數。

function printArea(Shape $shape) 
{ 
    echo "The area of `{$shape->getName()}` is {$shape->getArea()}" . PHP_EOL; 
} 

$shapes = []; 
$shapes[] = new Rectangle(10.0, 10.0); 
$shapes[] = new Triangle(10.0, 10.0); 

foreach ($shapes as $shape) { 
    printArea($shape); 
} 

一個例子運行會產生以下結果:

The area of `Rectangle` is 100 
The area of `Triangle` is 50 

關於你提到的有關PHP7穩定的第二個問題:是的,PHP7穩定,許多公司在生產中使用。