PHP Scope Resolution Operator Question
I'm having trouble with the MyClass::function();
style of calling methods and can't figure out why. Here's an example (I'm using Kohana framework btw):
class Test_Core
{
public $var1 = "lots of testing";
public function output()
{
$print_out = $this->var1;
echo $print_out;
}
}
开发者_如何学运维
I try to use the following to call it, but it returns $var1 as undefined:
Test::output()
However, this works fine:
$test = new Test();
$test->output();
I generally use this style of calling objects as opposed to the "new Class" style, but I can't figure out why it doesn't want to work.
Using this :
Test::output()
You are calling your method as a static one -- and static methods don't have access to instance properties, as there is no instance.
If you want to use a property, you must instanciate the class, to get an object -- and call the methods on that object.
A couple of links to the manual, as a reference :
- The Classes and Objects section -- you should really read this section ;-)
- Properties
- The Basics
- Static Keyword -- Interesting too, for this specific question ;-)
Quoting the last page I linked to :
Because static methods are callable without an instance of the object created, the pseudo-variable
$this
is not available inside the method declared as static.
And :
Calling non-static methods statically generates an
E_STRICT
level warning.
Static call vs instance call. You'll want to grasp these basic OOP concepts. Have a read of the static keyword as well:
http://www.php.net/manual/en/language.oop5.static.php
You can't use $this while a static call because $this is refers to object which is not created in your case.
Try Test_Core::output()
because you are using wrong class name
精彩评论