创建后的PHP使用对象
我从类中创建对象,方法如下:创建后的PHP使用对象,php,scope,Php,Scope,我从类中创建对象,方法如下: // ##### function.php ##### class Test{ function hello(){ echo "Hello World"; } } // ##### index.php ##### include 'function.php'; $test = new Test(); $test->hello(); include 'file2.php'; // ##### file2.php ##### $
// ##### function.php #####
class Test{
function hello(){
echo "Hello World";
}
}
// ##### index.php #####
include 'function.php';
$test = new Test();
$test->hello();
include 'file2.php';
// ##### file2.php #####
$test->hello(); // This line is not working !!!
“index.php”是我的索引页面,我包含了来自“files2.php”的索引文件内容。问题是当我想在“file2.php”中使用“$test
”对象时,我无法访问“$test->hello()
”。但当我从“file2.php”中的“Test()
”类再次创建新对象时,我可以访问“$Test->hello()
”。
我不想在include文件中重新创建相同的对象,在这种情况下我能做什么
非常感谢 您的语法似乎有误。当我这样声明类时:
在此处输入代码//#####function.php####
其他一切都是书面的
请注意,您在最后一行忘记了分号:
包括“file2.php”代码>您的file2.php中是否有任何内容以任何方式更改了$test?没有,只是我需要在子文件中使用此对象的方法。您的示例代码应该运行良好;在file2.php中尝试执行$test->hello()
时,是否出现任何错误(或写入日志的任何内容)?在file2.php中没有错误,$test变量,但我无法获取此对象的方法在标准php中,您的使用应该是100%有效的,您正在使用上面显示的确切文件进行测试吗?很抱歉我编辑了错误,但在我的源代码中一切都是正确的,但我不知道为什么子文件不能使用父文件对象?那么您的代码没有问题。我假设当我在index.php中创建对象时,每个文件都以开头,比如“$test=new test();”我可以在index.php中访问该对象中的所有方法,但当我想在file2.php中访问$test对象时,我可以看到$test变量,但无法获得方法。不是触发错误的行,php报告的实际错误
class Test { //not class Test()
function hello(){
echo "Hello World";
}
}