开发者

php: declaring static properties and methods

开发者 https://www.devze.com 2023-03-27 01:26 出处:网络
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 declar

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.


I think the description you quote is slightly unclear/ambiguous. They refer to $foo->my_static being not possible. This is later repeated in this statement:

Static properties cannot be accessed through the object using the arrow operator ->.

$foo::$my_static is possible though. The object instance just stands in for the class name, it doesn't really change how the static property is used and is mostly a convenience shortcut.


In almost all OO programming languages, you can access static members via an instance of the class. C++ allows this, Java allows this (although it gives a warning).

The reason for accessing statics through the class name and not through an instance of the class is mainly due to readability, which is why I suggest you do the same.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号