I have a structure like so:
main.php
include_once
func1.php
include_once
func2.php
These two files are include
'd inside main.php
.
I get the error below when I call a function switchboard()
from func1.php
inside finc2.php
.
Fatal error: Uncaught Error: Call to a member function switchboard() on null in func2.php:16
Stack trace:
#0 main.php(60): decode_func('{"auth":"...)
#1 {main} thrown in func2.php on line 16
Line 16 is where I call the function from func1.php
inside func2.php
—
switchboard() {}
. Is there a way to fix this besides include
ing func1.php
inside func2.php
?
func2.php
function decode($var) {
if() {return $var;}
else { $erm->switchboard('101', $var); }
}
func1.php
$erm = new CLASS() {
function switchboard($id, $var) {
if() {}
else {}
}
}
That would be because you use $erm
in the function decode()
, yet it is not included in the function's scope (let's keep in mind that contrarily to javascript, php functions do not inherit their surrounding scope)
You can declare decode
as an anonymous function and take advantage of use
to inject $erm
inside it, or make $erm
an argument of decode.
Just use
$erm to make sure to include it inside decode's scope:
$decode = function ($var) use ($erm) {
if() { return $var; }
else { $erm->switchboard('101', $var); }
};
Pass $erm
like any other parameter.
function decode ($var, $erm) {
if(false) { return $var; }
else { $erm->switchboard('101', $var); }
}