我想在调用数组时创建一个简单的命令。在本例中,它是 Remote 内的“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();
?>
任何帮助都会非常感激:)
最佳答案
您有一些语法错误,建议您应该阅读 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) 如果仅在类方法内使用,则应将此变量设为私有(private)
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();
?>
关于php - 在类内部调用数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6148175/