If I have for example the following class:
class Test {
private $field = array();
function __construct($field) {
$this->field = $field;
}
public function setField($field) {
$this->field = $field;
}
public function getField() {
return $this->field;
}
}
And I create an instance of this class:
$simpleArray = (1, 2, 3, 4);
$simpleTest = new Test($simpleArray);
How can I then print the value of simpleArray[2] in one line? I know this solution:
$saveArray = $simpleTest->getField();
echo $saveArray[2];
I want to know how to directly access array value after getField(), so that I don’t have to save the array to variable:
echo $simpleTest->getField()->....?
You could add a parameter which could serve as an index for what item to return, as can be seen below. Adding another method named something like
fieldAt($index)could be another solution.Another solution could be to implement the
ArrayAccessinterface, which would allow you to use the array access operators ([]) on your object: