2014-09-23 58 views
0

我已經被$this。我困惑知道用於闖民宅全球價值$this->somevaribale單獨行動......但我已經見過像

class ClassName 
{ 

private $array; //set up a variable to store our array 

/* 
* You can set your own array or use the default one 
* it will set the $this->array variable to whatever array is given in the construct 
* How the array works like a database; array('column_name' => 'column_data') 
*/ 
function __construct($array = array('fruit' => 'apple', 'vegetable' => 'cucumber')) { 
    $this->array = $array; 
} 

/* 
* Loops through the array and sets new variables within the class 
* it returns $this so that you may chain the method. 
*/ 
public function execute() { 

    foreach($this->array AS $key => $value) { 
     $this->$key = $value; //we create a variable within the class 
    } 

    return $this; //we return $this so that we can chain our method.... 
} 

} 

這裏$this代碼單獨叫.. .Am真的與此混淆。當我刪除$ this並用$ this->數組替換時出現錯誤。

所以我的問題是單獨調用$this以及它代表什麼。

Thanx的幫助。

+0

$這是指包含'$ array'的對象。 – Wold 2014-09-23 16:55:56

+1

查看流利的界面 – 2014-09-23 16:56:42

+0

@Wold包含$ array的對象意味着?? .. supose如果我打電話就像$ wold = new classname()..so $ this指的是$ wold ?? – 2014-09-23 16:58:23

回答

0

$這是PHP對象的參考。您可以瞭解更多有關對象以及如何$這部作品在PHP手冊here.

-1

A到你使用的術語夫婦更正:

  • $this是「當前」對象的引用,而不是「全球值「
  • 你不是在這裏」調用「任何東西; 功能被稱爲,你僅僅使用$this(這又是拿着對象的變量)

所以,return $this返回當前對象作爲方法的返回值。這通常只是做是爲了方便流暢的界面,一種風格,你可以編寫代碼,如:

$foo->bar()->baz() 

因爲bar()返回一個對象($this對象),您可以直接調用之後其方法baz()

+0

所以這裏$ foo-> bar()=== $這裏面的類? – 2014-09-23 17:25:02

+0

'bar()','$ this'裏面==='$ foo'。 – deceze 2014-09-23 17:43:09

+0

所以這裏當我運行像$ name = new classname(),$ name-> execute().so $ name-> execute === $ foo right? – 2014-09-23 17:47:04

0

一個類是一種對象的「藍圖」,反之亦然,對象是一個類的實例。當在班級中使用$this時,它指的是它本身。

$hi = new ClassName(); 
$hi->execute()->method()->chaining()->is_like_this(); 

$hiClassName對象,並返回​​對象本身的功能。

$ha = $hi->execute(); 
// $ha refers to a ClassName object. 

方法鏈接(流利的接口)允許一個收拾代碼,如果一個正常調用該對象的方法很多:

$hi->doSome(); 
$hi->doAnotherThing(); 
$hi->thirdMethodCall(); 
$hi->etcetera(); 

將成爲

$hi->doSome() 
    ->doAnotherThing() 
    ->thirdMethodCall() 
    ->etcetera(); 
+0

so $這裏面的類是指類的對象?/ ie $ hi? – 2014-09-23 17:22:37

+0

確實,'$ this'指的是調用方法的對象。 – 2014-09-23 17:53:49