CodeIgniter Forums

Full Version: A fairly dumb question...
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Lovecannon[/eluser]
This has always confused me, what is the main difference in using -> and :: for calling methods of a class? Is :: only for static methods? and can static methods be called via ->? I feel dumb for asking this question..

El Forum

[eluser]Hyra[/eluser]
The main difference, if not the only one, is that you use the double colon for static members, and the arrow for members


Static Member
Code:
class Foo
{
   public static $my_static = 'foo';

   public function staticValue() {
       return self::$my_static;
   }
}

class Bar extends Foo
{
   public function fooStatic() {
       return parent::$my_static;
   }
}


print Foo::$my_static . "\n";

$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n";      // Undefined "Property" my_static

// $foo::my_static is not possible

print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";

Static method
Code:
class Foo {
   public static function aStaticMethod() {
       // ...
   }
}

Foo::aStaticMethod();

So .. :: can only be used for static (non-changing) methods/members

El Forum

[eluser]Negligence[/eluser]
Basically, yes.

--> is used for objects (instantiations of a class), while :: accesses a classes' methods directly without the need for an object. You can use :: to access non-static methods, but static methods must be called with ::.

I would recommend reading the OOP section in the PHP documentation. This is pretty basic knowledge you should have.

El Forum

[eluser]Lovecannon[/eluser]
I learned PHP 4 years ago on PHP4, I never really used static variables or methods in PHP, even when PHP5 came out.