I'm trying to manually reverse an array in PHP. The array is entered through a form, exploded and then reversed. I can get the code working without classes, but I am currently being taught about classes, so I'm trying to make my current code work with classes too.
<?php
class reverseArray{
public function setSting(){
$string = $_POST['numberInput'];
return $string;
}
public function explodeString(){
$array = explode(' ', $string);
return $array;
}
public function setArray(){
$arrayToEcho = explodeString();
return $arrayToEcho;
}
public function returnArray(){
for ($i = count($arrayToEcho) - 1; $i >=0 ; $i--){
echo " ";
$arrayToEcho[$i] = $arrayToEcho[$i];
echo $arrayToEcho[$i];
}
}
}
?>
I'm still very unsure if PHP classes and how to call on returns etc, so if someone could point me in the right direction? I currently get no errors or warnings, but also no output!
Looking up variable scopes will help you. You need a class property in order to use it in other methods, or functions. Right now, $string
is only available inside the function it is defined at. You can declare a class property and use the $this
accessor.
class reverseArray{
public $string;
public function setString(){
$this->string = $_POST['numberInput'];
return $this->string;
}
public function explodeString(){
$array = explode(' ', $this->string);
return $array;
}
}
I think a better usage for this class would be
public function setString($str){
$this->string = $str;
}
This would allow this class to be re-used as you can use any string inside the class, not just $_POST['numberInput']