Static Methods
Posted: Wed Jul 19, 2006 12:15 pm
I'm reading the code below from this website and came accross this explanation and example code
It says that the method that was declared static cannot be called from an object instance. Well I'm testing this code and sure enough it DOES let me call static Foo() from an object instance. I get no error. Is the example just wrong or is there a setting in the php.ini that enforces this?
Script: static_method.php
http://www.sitepoint.com/print/1192Essentially, all methods can be called statically in PHP5 anyway, as was possible in PHP4. However, the static keyword prevents a method declared with it from being called via an object instance, as the example demonstrates.
It says that the method that was declared static cannot be called from an object instance. Well I'm testing this code and sure enough it DOES let me call static Foo() from an object instance. I get no error. Is the example just wrong or is there a setting in the php.ini that enforces this?
Code: Select all
<?php
class MyStatic {
static function Foo() {
return 'This is foo()';
}
function Bar() {
return 'This is bar()';
}
}
echo ( MyStatic::foo().'<br />' );
echo ( MyStatic::bar().'<br />' );
$obj = new MyStatic();
# Fatal error - cannot call static method via object instance
// echo ( $obj->foo().'<br />' );
echo ( $obj->bar().'<br />' );
?>