我有以下问题
class class_name {
function b() {
// do something
}
function c() {
function a() {
// call function b();
}
}
}
当我像往常一样调用函数时: $this->b();我收到此错误:Using $this when not in object context in C:...
函数 b() 被声明为 public
有什么想法吗?
我将不胜感激任何帮助
Thanks
功能a()
在方法内部声明c()
.
<?php
class class_name {
function b() {
echo 'test';
}
function c() {
}
function a() {
$this->b();
}
}
$c = new class_name;
$c->a(); // Outputs "test" from the "echo 'test';" call above.
在方法内使用函数的示例(不推荐)
您的原始代码不起作用的原因是变量的范围。$this
仅在类的实例中可用。功能a()
不再是它的一部分,因此解决问题的唯一方法是将实例作为变量传递给类。
<?php
class class_name {
function b() {
echo 'test';
}
function c() {
// This function belongs inside method "c". It accepts a single parameter which is meant to be an instance of "class_name".
function a($that) {
$that->b();
}
// Call the "a" function and pass an instance of "$this" by reference.
a(&$this);
}
}
$c = new class_name;
$c->c(); // Outputs "test" from the "echo 'test';" call above.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)