2011-05-27 21 views
2

我想在調用數組時創建一個簡單的命令。在這種情況下,它將是遙控器內的ON按鈕。 (說明性概念)。但不工作(語法錯誤)。調用類中的數組值

這是我的一段代碼:

<?php 
class remoteControl{ 

    public $operate = array("ON", "OFF", "UP","DOWN"); 



    public function pressButton($operate("0")){ 
    echo "You have pressed ". $this->operate; 
    } 
} 

$control_01 = new remoteControl(); 

echo $control_01-> pressButton(); 

?> 

任何幫助將是非常感激:)

回答

3

你有幾個語法錯誤提示你應該閱讀PHP manual有關基礎知識。

你的代碼(格式化):

<?php 
class remoteControl { 
    public $operate = array("ON", "OFF", "UP","DOWN"); // 1) 

    public function pressButton($operate("0")) { // 2), 3), 4) 
     echo "You have pressed ". $this->operate; // 5) 
    } 
} 

$control_01 = new remoteControl();     
echo $control_01-> pressButton(); 

?> 

1)如果只使用類方法中使用

2)陣列,你應該讓這個私有變量:$操作[0] - read more

3)不要使用字符串作爲索引(「0」) - 它會工作,但它的不必要的類型鑄造

4)最後,此行應該是這樣的:

public function pressButton($operate = 0) { 

這意味着,如果你沒有明確提供一個參數將有0值 - 因爲4 read more about function arguments

5) )它應該是:

echo "You have pressed ". $this->operate[$operate]; 

編輯:所有代碼:

<?php 
class remoteControl { 
    private $operate = array("ON", "OFF", "UP", "DOWN"); 

    public function pressButton($operate = 0) { 
     echo "You have pressed ". $this->operate[$operate]; 
    } 
} 

$control_01 = new remoteControl();     
echo $control_01->pressButton(); 

?> 
2

沒有明確讓你的意圖,與你的代碼, 你彷彿傳遞一個元素操作數組到你的函數。 希望這個代碼可以幫助:http://codepad.org/CYVT7hI5

<?php 
class remoteControl{ 

    public $operate = array("ON", "OFF", "UP","DOWN"); 



    public function pressButton($index){ 
    echo "You have pressed ". $this->operate[$index]; 
    } 
} 

$control_01 = new remoteControl(); 

echo $control_01->pressButton(1); 

?>