PHP:从严重死亡的类中调用私有方法 [英] PHP: Calling a private method from within a class dying badly

查看:70
本文介绍了PHP:从严重死亡的类中调用私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这听起来有些令人费解.手指交叉,我清楚地碰到了.

So this might sound a little convoluted. Fingers crossed I come across clearly.

我正在使用PHP的MVC框架.

I'm working in an MVC framework in PHP.

我加载了调用帮助程序的控制器/report/index

I load a controller /report/index which calls to a helper

<? class ReportController extends Controller { 
        public function index() {
            $foo = MainReport::get_data($_REQUEST);
        }

   }
 ?>

在帮手内部

<? class MainReport extends foo {
        public function get_data($_REQUEST) {
            // do stuff
            return $stuff_done;
        }

 }
?>

我运行起来就像^,这一切都很好.不幸的是,我想这样运行:

It I run it like ^this all's well and good. Unfortunately, I want to run it like this:

<? class MainReport extends foo {
        private function do_stuff() { 
            // do even better stuff here!
            return $better_stuff;
        }
        public function get_data($_REQUEST) {
            // do stuff
            $x = $this->do_stuff();    
        }

 }
?>

不幸的是……当我尝试从我从其他地方调用的类中调用私有函数时……(哇,那是满嘴的)……一切都消亡了.死得非常非常严重,我什至都没有收到错误消息.

Unfortunately... when I try and call a private function from within a class that I've called from elsewhere... (whew, that's a mouthful) ... everything dies. Dies so very very badly that I don't even get an error.

在我看来,我似乎遇到了一种令人难以置信的语法问题,但是如何从类中正确访问私有函数呢?

It seems obvious to me that I'm having an incredibly dorky sort of syntax issue of some sort... but how do I correctly access private functions from within a class?

也许是这样的: self :: do_stuff();

Maybe something like: self::do_stuff();

如何声明和访问私有类变量?

What about declaring and accessing private class variables?

 private $bar = array();

任何帮助都将受到欢迎.

Any help would be welcome.

推荐答案

您正在从静态上下文中调用函数

You are calling your function from a static context,

MainReport::get_data($_REQUEST)

因此$ this在该函数中不存在.

therefore $this does not exist while inside that function.

如果要在静态上下文中调用另一个类函数,则还必须静态调用它.

If you want to call another class function while inside a static context, you have to also call it statically.

public function get_data($_REQUEST) {
        // do stuff
        $x = MainReport::do_stuff();    
    }

或者,您可以在原始调用中创建类的实例并使用该实例:

Alternatively, you can create an instance of your class in the original call and use the instance:

$myMainReport = new MainReport();
$myMainReport->get_data($_REQUEST);

然后您的班级代码将按预期工作

Then your class code will work as expected

这篇关于PHP:从严重死亡的类中调用私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆