2016-11-21 104 views
3

我正在閱讀關於Laravel here的簡短教程。因爲我不是在一般laravel或發展經歷我想知道什麼的這部分代碼不正是:Laravel在用冒號聲明函數後調用模型

public function approve(): User 

因爲它是在我看來,它是隻調用來自內部模型一樣的東西功能如下:

App\User:: 

這兩種方法有什麼區別?

回答

3

不,它們不一樣。第一個代碼是利用PHP 7的return type declerations

它說,該方法必須返回User類的實例,或者PHP將拋出一個TypeError你。您還可以指定類的FQN定義返回類型聲明時:

public function approve(): \App\User 

定義接口時,這是特別有用的:

interface CommentsIterator extends Iterator { 
    function current(): Comment; 
    // This enforces that any implementation of current() 
    // method, must return an instance of Comment class. 
} 

看看其他的RFC自己的方式進入PHP 7:
https://secure.php.net/manual/en/migration70.new-features.php

用Jeffrey在PHP 7上的截屏新特性:
https://laracasts.com/series/php7-up-and-running/episodes/3

但是第二個代碼(App\User::whatever())只是調用App\User類的靜態方法whatever()。它與強制返回類型的第一個代碼示例無關。

4

第一個例子您分享:

public function approve(): User 

簡直是PHP7的功能,它允許你使用靜態類型的編程習慣用PHP。實質上,這個新的函數簽名告訴你這個函數需要返回User類型,否則它將拋出TypeError異常。

第二個例子您分享:

App\User:: 

使用所謂的範圍解析操作符::)該運營商允許你調用職業等級/靜態方法。在Laravel例如,這將是這樣的:

App\User::Find(1); 

App\User::Where('id', 1); 

和這些從對象水平的方法,其將被稱爲像這樣不同:

$user = new App\User(); 
$user->id = 1; 
$user->save() 

通知類實例使用->運算符。

您可以瞭解更多關於什麼我在下面的鏈接中提到:

https://secure.php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration

http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php

https://laravel.com/docs/5.3/eloquent

祝您好運!