I am trying to count an array from within a class in PHP but I get a "Countable" error. The same thing outsite a class is working as expected.
The non-class working code is this one.
$numbers = array(
array(0,0,0,0,0,6,6,6,6,4,4,7,7,3,3,3,3,8,5,5,2,2,2,2,6,6,6,6,7,7,7,7,5,5,5,5,1,1,1,1,8,7,7,3,3,3,3,4,4,4,4,6,6,5,5,5,5,8,7,7,7,7,5,5,5,3,3,2,2,2,2,1,1,8,4,4,4,2,2,6,6),
array(0,0,0,0,7,7,7,7,7,0,0,4,4,6,6,6,6,6,4,4,1,1,6,6,6,3,3,3,3,9,9,9,9,7,7,7,7,7,8,5,5,5,6,6,6,6,8,7,7,7,8,4,4,4,4,1,1,1,1,6,6,6,6,2,2,2,2,8,7,7,7),
array(6,6,6,3,3,3,3,8,5,5,5,5,0,0,0,0,4,4,5,5,5,5,0,0,0,5,5,5,4,4,4,4,1,1,1,1,5,5,5,5,5,7,7,7,1,1,1,8,2,2,2,2,9,9,9,9,9,4,4,4,4),
array(0,0,0,0,0,0,1,1,1,1,0,0,0,2,2,2,2,2,9,9,9,9,9,7,7,7,7,7,2,2,2,2,1,1,1,1,3,3,3,3,3,8,4,4,4,4,1,1,1,9,9,9,9,9,3,3,3,3,6,6,6,6,6,4,4,4,4,4,5,5,5,5,5),
array(0,0,0,0,5,5,5,5,7,7,1,1,1,1,4,4,4,4,0,0,0,0,0,5,5,1,1,1,1,2,2,2,2,6,6,4,4,4,4,4,0,0,0,0,0,1,1,1,1,1,3,3,3,3,3,3,6,6,6,6,7,7,7,7,8,2,2,2,2,2,4,4,3,3,3)
);
function myFunc() {
global $numbers;
for ($number = 0; $number < count($numbers); $number ) {
var_dump($numbers[$number]);
}
}
myFunc();
The non-working in-class code is this one, which throws a PHP Warning: count(): Parameter must be an array or an object that implements Countable in HelloWorld.php on line 13 (Line 12 in the example below, due to php tag missing)
class MyClass {
public $numbers = array(
array(0,0,0,0,0,6,6,6,6,4,4,7,7,3,3,3,3,8,5,5,2,2,2,2,6,6,6,6,7,7,7,7,5,5,5,5,1,1,1,1,8,7,7,3,3,3,3,4,4,4,4,6,6,5,5,5,5,8,7,7,7,7,5,5,5,3,3,2,2,2,2,1,1,8,4,4,4,2,2,6,6),
array(0,0,0,0,7,7,7,7,7,0,0,4,4,6,6,6,6,6,4,4,1,1,6,6,6,3,3,3,3,9,9,9,9,7,7,7,7,7,8,5,5,5,6,6,6,6,8,7,7,7,8,4,4,4,4,1,1,1,1,6,6,6,6,2,2,2,2,8,7,7,7),
array(6,6,6,3,3,3,3,8,5,5,5,5,0,0,0,0,4,4,5,5,5,5,0,0,0,5,5,5,4,4,4,4,1,1,1,1,5,5,5,5,5,7,7,7,1,1,1,8,2,2,2,2,9,9,9,9,9,4,4,4,4),
array(0,0,0,0,0,0,1,1,1,1,0,0,0,2,2,2,2,2,9,9,9,9,9,7,7,7,7,7,2,2,2,2,1,1,1,1,3,3,3,3,3,8,4,4,4,4,1,1,1,9,9,9,9,9,3,3,3,3,6,6,6,6,6,4,4,4,4,4,5,5,5,5,5),
array(0,0,0,0,5,5,5,5,7,7,1,1,1,1,4,4,4,4,0,0,0,0,0,5,5,1,1,1,1,2,2,2,2,6,6,4,4,4,4,4,0,0,0,0,0,1,1,1,1,1,3,3,3,3,3,3,6,6,6,6,7,7,7,7,8,2,2,2,2,2,4,4,3,3,3)
);
public function myFunc() {
global $numbers;
for ($number = 0; $number < count($numbers); $number ) {
var_dump($numbers[$number]);
}
}
}
$testMyClass = New MyClass;
$testMyClass->myFunc();
EDIT: I did a gettype() against $numbers and I get NULL, but I still don't understand why.
CodePudding user response:
As suggested by @mitkosoft, changing global with $this-> did the trick.
Thank you!
CodePudding user response:
I'm putting my comment as an answer in order to close the ticket:
Changing global $numbers;
with $numbers = $this->numbers;
will do the trick. global
is not the right way to access the defined class variables.