简体   繁体   中英

php: declaring static properties and methods

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM