Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

object - PHP 5: const vs static

In PHP 5, what is the difference between using const and static?

When is each appropriate? And what role does public, protected and private play - if any?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the context of a class, static variables are on the class scope (not the object) scope, but unlike a const, their values can be changed.

class ClassName {
    static $my_var = 10;  /* defaults to public unless otherwise specified */
    const MY_CONST = 5;
}
echo ClassName::$my_var;   // returns 10
echo ClassName::MY_CONST;  // returns 5
ClassName::$my_var = 20;   // now equals 20
ClassName::MY_CONST = 20;  // error! won't work.

Public, protected, and private are irrelevant in terms of consts (which are always public); they are only useful for class variables, including static variable.

  • public static variables can be accessed anywhere via ClassName::$variable.
  • protected static variables can be accessed by the defining class or extending classes via ClassName::$variable.
  • private static variables can be accessed only by the defining class via ClassName::$variable.

Edit: It is important to note that PHP 7.1.0 introduced support for specifying the visibility of class constants.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...