3v4l.org

run code in 300+ PHP versions simultaneously
<?php class SomeClass { public $array; public $content; public $item; public function someMethod() { $this->array = [ "testing" => "testing one two three", "apples" => "red", "oranges" => "orange", ]; foreach($this->array as $this->item) { // I pass $this->item down inside the loop echo $this->content; // this here is looped } } } $class = new SomeClass(); /** * I want to access $this->item without having to do a loop * * I don't want this e.g: foreach($this->array as $this->item) { * echo $this->item; * } * * but instead I just want to do this: foreach($this->array as $this->item) { * echo $this->content; this here will output the content * } * * and inside `$class->content` it has the variable that is passed down: `$this->item`. * that way I don't HAVE to write a loop and all I have to do is write `$this->content`. * that means, I don't want to write a loop! I just want to write what the loop outputs! * and I'm having troubles getting the item that is passed inside of the loop. */ // I want to do this but I can't figure out how to access $class->item outside of loop $class->content = $class->item; // I could do something that works: foreach($class->array as $class->item) { echo $class->item; } // but I want to access `$class->item` outside of the loop and use it in: $class->content = $class->item; // then call the method that will loop and echo the property `content` $class->someMethod();
Output for 8.0.0 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
Warning: foreach() argument must be of type array|object, null given in /in/WTD0v on line 52
Output for 5.6.0 - 5.6.30, 7.0.0 - 7.0.31, 7.1.0 - 7.1.21, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33
Warning: Invalid argument supplied for foreach() in /in/WTD0v on line 52

preferences:
85.59 ms | 1731 KiB | 4 Q