views:

138

answers:

2

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.

A: 

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

webbiedave
+3  A: 

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 :


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.

Pascal MARTIN