Reputation: 1000
I want to create a simple command when an array is called. In this case it would be the ON button inside a remote control. (Illustrative concept). But is not working (syntax error).
This is my piece of code:
<?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();
?>
Any help would be very greatful :)
Upvotes: 2
Views: 1147
Reputation: 27995
You have few syntax errors suggesting that you should read PHP manual about basics.
Your code (formatted):
<?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) you should make this variable private if used only inside class methods
2) using arrays: $operate[0] - read more
3) don't use string as index ("0") - it will work, but its unnecessary type casting
4) finally, this line should be something like this:
public function pressButton($operate = 0) {
which means that if you don't explicitly provide an argument it will have value 0 - read more about function arguments
5) because of 4) it should be:
echo "You have pressed ". $this->operate[$operate];
EDIT: Whole code:
<?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();
?>
Upvotes: 3
Reputation: 43235
did not clearly get what you intent to do with your code , you seem to pass one element of operate array to your function . hope this code helps : 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);
?>
Upvotes: 2