Before we go any further: Please, get into the habbit of always specifying the visibility/accessibility of your object's properties and methods. Instead of writing
function foo() {//php 4 style method }
Write:
public function foo() { //this'll be public } protected function bar() { //protected, if this class is extended, I'm free to use this method } private function foobar() { //only for inner workings of this object }
first off, your first example A::foo will trigger a notice (calling a non-static method statically always does this).
Secondly, in the second example, when calling A::foo(), PHP doesn't create an on-the-fly instance, nor does it call the method in the context of an instance when you called $a->foo() (which will also issue a notice BTW). Statics are, essentially, global functions because, internally, PHP objects are nothing more than a C struct, and methods are just functions that have a pointer to that struct. At least, that's the gist of it, more details here
The main difference (and if used properly benefit) of a static property or method is, that they're shared over all instances and accessible globaly:
class Foo { private static $bar = null; public function __construct($val = 1) { self::$bar = $val; } public function getBar() { return self::$bar; } } $foo = new Foo(123); $foo->getBar();//returns 123 $bar = new Foo('new value for static'); $foo->getBar();//returns 'new value for static'
As you can see, the static property $bar can't be set on each instance, if its value is changed, the change applies for all instances.
If $bar were public, you wouldn't even need an instance to change the property everywhere:
class Bar { public $nonStatic = null; public static $bar = null; public function __construct($val = 1) { $this->nonStatic = $val; } } $foo = new Bar(123); $bar = new Bar('foo'); echo $foo->nonStatic, ' != ', $bar->nonStatic;//echoes "123 != foo" Bar::$bar = 'And the static?'; echo $foo::$bar,' === ', $bar::$bar;// echoes 'And the static? === And the static?'
Look into the factory pattern, and (purely informative) also peek at the Singleton pattern. As far as the Singleton pattern goes: Also google why not to use it. IoC, DI, SOLID are acronyms you'll soon encounter. Read about what they mean and figure out why they're (each in their own way) prime reasons to not go for Singletons