[英]php oop call method from inside the method from the same class
我有以下问题
class class_name {
function b() {
// do something
}
function c() {
function a() {
// call function b();
}
}
}
当我像往常一样调用 function 时: $this->b(); 我收到此错误:在 C 中不在 object 上下文中时使用 $this:...
function b() 被声明为公共
有什么想法吗?
我会很感激任何帮助
谢谢
function 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.
在方法中使用 function 的示例(不推荐)
您的原始代码不起作用的原因是因为变量的 scope 。 $this
仅在 class 的实例中可用。 function a()
不再是它的一部分,因此解决问题的唯一方法是将实例作为变量传递给 class。
<?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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.