Referring to http://php.net/manual/en/language.oop5.static.php,
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
Why does the example instantiate the class ($foo = new Foo();) before print $foo::$my_static? As per the above statement only
print Foo::$my_static
OR
$classname = 'Foo';
print $classname::$my_static
is correct.
example1.php
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::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0
?>
example2.php
<?php
class Foo{
static $myVar="foo";
public static function aStaticMethod(){
return self::$myVar;
}
}
$foo=new Foo;
print $foo->aStaticMethod();
?>
The above example doesn't give any error. Is it a good practise to access a static method with an instantiated class object?
thank you.