在Class中调用数组值

时间:2011-05-27 05:27:51

标签: php arrays class function object

我想在调用数组时创建一个简单的命令。在这种情况下,它将是遥控器内的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();

?> 

任何帮助都会非常棒:)

2 个答案:

答案 0 :(得分: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)使用数组:$ operate [0] - read more

3)不要使用字符串作为索引(“0”) - 它会起作用,但是它不必要的类型转换

4)最后,这一行应该是这样的:

public function pressButton($operate = 0) {

这意味着如果您没有明确提供参数,它将具有值0 - read more about function arguments

5)因为4)它应该是:

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();

?>

答案 1 :(得分: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);

?>