I have two classes, class A and class B, and in a function in class A I want to call a function in B, but the it also requires constants from another file. After requiring both the config.php and classB.php files, I am able to create an instance of class B, but when I try to call the function in B, it gives me a warning saying the constant has not been defined.
In config.php:
$constant = 'blah';
Inside class A I have:
function functionA() {
require_once "config.php";
require_once "classB.php";
$b = new B();
$b -> functionB($constant);
}
The call to function B is giving an error saying $constant is not defined, but when I call new B() there is no problem. Am I doing something wrong?
答案 0 :(得分:0)
Aron是对的。在这种情况下,您希望使用include
或require
。您必须确保您所包含的文件中没有函数或类声明。
这是因为每次调用方法时都不会发生需求,只是第一次调用。随后对该方法的调用将导致未定义的变量错误。
其他热门提示:您可以从包含的文件中返回值,将它们直接分配给变量
a.php只会:
return 'abc';
B.php:
Class B {
public static function load()
{
$x = include 'A.php';
var_dump($x);
}
}
我想你的代码应如下所示:
function functionA() {
require "config.php";
require_once "classB.php";
$b = new B();
$b -> functionB($constant);
}
答案 1 :(得分:-1)
使用包含'config.php';
的句子而不是require_once,如果你的config.php文件只有变量声明。