php oop调用方法来自同一个类的方法
发布时间:2020-12-13 21:42:25 所属栏目:PHP教程 来源:网络整理
导读:我有以下问题 class class_name {function b() { // do something}function c() { function a() { // call function b(); }}} 当我像往常一样调用函数时:$this- b();我收到此错误:在C中的对象上下文中使用$this:… function b()声明为public 有什么想法吗
我有以下问题
class class_name { function b() { // do something } function c() { function a() { // call function b(); } } } 当我像往常一样调用函数时:$this-> b();我收到此错误:在C中的对象上下文中使用$this:… function b()声明为public 有什么想法吗? 我会感激任何帮助 谢谢 解决方法
函数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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |