CodeIgniter Forums
A fairly dumb question... - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: A fairly dumb question... (/showthread.php?tid=6538)



A fairly dumb question... - El Forum - 03-03-2008

[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..


A fairly dumb question... - El Forum - 03-03-2008

[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


A fairly dumb question... - El Forum - 03-03-2008

[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.


A fairly dumb question... - El Forum - 03-03-2008

[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.