2013-07-24 65 views
0

我試圖理解當試圖在Laravel中創建數據庫時方括號的含義。如果我有一個帶有2個字段標題和正文的表格,我想知道爲什麼使用方括號而不是array()。方括號是用於簡短形式還是用於組織?似乎方括號不僅僅用於種子數據庫。laravel php方括號定義

public function run() 
{ 
    $posts = [ 
     [ 'title' => 'My first post', 'body' => 'My post' ], 
     [ 'title' => 'My second post', 'body' => 'My post' ] 
    ]; 
    DB::table('posts')->insert($posts); 
} 
+0

請參閱http://php.net/manual/en/language.types.array.php。 「從PHP 5.4開始,您還可以使用短陣列語法,它用[]替換array()。」 – Deinumite

回答

2

這是一樣的:

public function run() 
{ 
    $posts = array(
     array('title' => 'My first post', 'body' => 'My post'), 
     array('title' => 'My second post', 'body' => 'My post') 
    ); 
    DB::table('posts')->insert($posts); 
} 

它是較新的(> = PHP 5.4)定義的陣列的短路。

1

你看到的是短陣列語法。 2年前它是implemented,可用於PHP版本=> 5.4。

<?php 
$array = array(
    "foo" => "bar", 
    "bar" => "foo", 
); 

// as of PHP 5.4 
$array = [ 
    "foo" => "bar", 
    "bar" => "foo", 
]; //short syntax 
?> 

爲了兼容性,我建議使用前者。但兩者在功能上是相同的。

請參閱數組here的文檔。

如果您需要更多信息,請參閱RFC