PHP: Calling a private method from within a class dying badly
So this might sound a little convoluted. Fingers crossed I come across clearly.
I'm working in an MVC framework in PHP.
I load a controller /report/index which calls to a helper
<? class ReportController extends Controller {
public function index() {
$foo = MainReport::get_data($_REQUEST);
}
}
?>
Inside the helper
<? 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?
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)
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.
i.e.
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
I've just found that self:: does work as well
if I want to have private class variables, I can declare and access them using
private static $foo
and
self::$foo = "foo";
additionally a private function can be accessed with
self::function_foo();
精彩评论