PHP 5:常量与静态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1685922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:31:05  来源:igfitidea点击:

PHP 5: const vs static

phpobjectconstantsclass-designstatic-members

提问by Chris Jacob

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

在 PHP 5 中,使用const和 有static什么区别?

When is each appropriate? And what role does public, protectedand privateplay - if any?

什么时候合适?和什么样的作用呢publicprotectedprivate游戏-如果有的话?

回答by Matt Huggins

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.

在类的上下文中,静态变量在类范围(而不是对象)范围内,但与 const 不同的是,它们的值可以更改。

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、protected 和 private 与常量(始终是公共的)无关;它们只对类变量有用,包括静态变量。

  • 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.
  • 公共静态变量可以通过 ClassName::$variable 在任何地方访问。
  • 定义类或扩展类可以通过 ClassName::$variable 访问受保护的静态变量。
  • 私有静态变量只能由定义类通过 ClassName::$variable 访问。


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

编辑:重要的是要注意PHP 7.1.0 引入了对指定类常量可见性的支持

回答by luoshiben

One last point that should be made is that a const is always static and public. This means that you can access the const from within the class like so:

应该指出的最后一点是 const 始终是静态和公共的。这意味着您可以从类中访问 c​​onst,如下所示:

class MyClass
{
     const MYCONST = true;
     public function test()
     {
          echo self::MYCONST;
     }
}

From outside the class you would access it like this:

从课堂外,您可以像这样访问它:

echo MyClass::MYCONST;

回答by Mike Borozdin

Constantis just a constant, i.e. you can't change its value after declaring.

常量只是一个常量,即声明后不能更改其值。

Staticvariable is accessible without making an instance of a class and therefore shared between all the instances of a class.

静态变量无需创建类的实例即可访问,因此在类的所有实例之间共享。

Also, there can be a staticlocal variable in a function that is declared only once (on the first execution of a function) and can store its value between function calls, example:

此外,函数中可以有一个静态局部变量,该变量仅声明一次(在函数第一次执行时)并且可以在函数调用之间存储其值,例如:

function foo()
{
   static $numOfCalls = 0;
   $numOfCalls++;
   print("this function has been executed " . $numOfCalls . " times");
}

回答by Wilt

When talking about class inheritance you can differentiate between the constant or variable in different scopes by using selfand statickey words. Check this example which illustrates how to access what:

在谈论类继承时,您可以使用selfstatic关键字来区分不同范围内的常量或变量。检查这个例子,它说明了如何访问什么:

class Person
{
    static $type = 'person';

    const TYPE = 'person';

    static public function getType(){
        var_dump(self::TYPE);
        var_dump(static::TYPE);

        var_dump(self::$type);
        var_dump(static::$type);
    }
}

class Pirate extends Person
{
    static $type = 'pirate';

    const TYPE = 'pirate';
}

And then do:

然后做:

$pirate = new Pirate();
$pirate::getType();

or:

或者:

Pirate::getType();

Output:

输出:

string(6) "person" 
string(6) "pirate" 
string(6) "person" 
string(6) "pirate"


In other words self::refers to the static property and constant from the same scope where it is being called (in this case the Personsuperclass), while static::will access the property and constant from the scope in run time (so in this case in the Piratesubclass).

换句话说self::,从调用它的同一个范围(在这种情况下是Person超类)中引用静态属性和常量,而static::将在运行时从范围访问属性和常量(因此在这种情况下是在Pirate子类中)。

Read more on late static binding here on php.net.
Also check the answer on another question hereand here.

在 php.net 上阅读有关后期静态绑定的更多信息
还要在这里这里检查另一个问题的答案。

回答by alexn

Declaring a class method or property as static makes them accessible without needing an instantiation of the class.

将类方法或属性声明为静态使它们无需实例化即可访问。

A class constant is just like a normal constant, it cannot be changed at runtime. This is also the only reason you will ever use const for.

类常量就像普通常量一样,不能在运行时更改。这也是您将使用 const 的唯一原因。

Private, public and protected are access modifiers that describes who can access which parameter/method.

Private、public 和 protected 是描述谁可以访问哪个参数/方法的访问修饰符。

Public means that all other objects gets access. Private means that only the instantiated class gets access. Protected means that the instantiated class and derived classes gets access.

公共意味着所有其他对象都可以访问。Private 意味着只有实例化的类才能访问。受保护意味着实例化类和派生类可以访问。

回答by Jijo John

Here's the things i learned so far about static members , constant variables and access modifiers(private,public and protected). Constant

这是我到目前为止学到的关于静态成员、常量变量和访问修饰符(私有、公共和受保护)的内容。 持续的

Definition

定义

Like the name says values of a constant variable can't be changed.Constants differ from normal variables in that you don't use the $ symbol to declare or use them.

顾名思义,常量变量的值不能更改。常量与普通变量的不同之处在于您不使用 $ 符号来声明或使用它们。

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.

该值必须是常量表达式,而不是(例如)变量、属性、数学运算的结果或函数调用。

Note : The variable's value can not be a keyword (e.g. self, parent and static).

注意:变量的值不能是关键字(例如 self、parent 和 static)。

Declaring a constant in php

在 php 中声明一个常量

<?php
class constantExample{

   const CONSTANT = 'constant value'; //constant

 }
?>

Constant's scope is global and can be accessed using a self keyword

Constant 的作用域是全局的,可以使用 self 关键字访问

<?php
class MyClass
{
    const CONSTANT = 'constant value';

    function showConstant() {
        echo  self::CONSTANT . "\n";
    }
}

echo MyClass::CONSTANT . "\n";

$classname = "MyClass";
echo $classname::CONSTANT . "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::CONSTANT."\n"; // As of PHP 5.3.0

?>

Static

静止的

Definition

定义

Static keyword can be used for declaring a class, member function or a variable.Static members in a class is global can be accessed using a self keyword as well.Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can). If no visibility declaration ( public, private, protected ) is used, then the property or method will be treated as if it was declared as public.Because static methods are callable without an instance of the object created.

静态关键字可用于声明类、成员函数或变量。类中的静态成员是全局的,也可以使用 self 关键字访问。将类属性或方法声明为静态使它们无需实例化即可访问. 声明为静态的属性不能用实例化的类对象访问(尽管静态方法可以)。如果未使用可见性声明(public、private、protected),则属性或方法将被视为已声明为 public。因为静态方法无需创建对象的实例即可调用。

Note : the pseudo-variable $this is not available inside the method declared as static.Static properties cannot be accessed through the object using the arrow operator ->

As of PHP 5.3.0, it's possible to reference the class using a variable. The >variable's value cannot be a keyword (e.g. self, parent and static).

注意:伪变量 $this 在声明为静态的方法中不可用。不能使用箭头操作符通过对象访问静态属性 ->

从 PHP 5.3.0 开始,可以使用变量来引用类。>variable 的值不能是关键字(例如 self、parent 和 static)。

Static property example

静态属性示例

<?php
class Foo
{
    public static $my_static = 'foo'; //static variable 

    public static function staticValue() { //static function example
        return self::$my_static;  //return the static variable declared globally
    }
}

?>

Accessing static properties and functions example

访问静态属性和函数示例

 <?php
     print Foo::$my_static . "\n";

    $foo = new Foo();
    print $foo->staticValue() . "\n";
    print $foo->my_static . "\n";      // Undefined "Property" my_static 

    print $foo::$my_static . "\n";
    $classname = 'Foo';
    print $classname::$my_static . "\n"; // As of PHP 5.3.0

    print Bar::$my_static . "\n";
    $bar = new Bar();
    print $bar->fooStatic() . "\n";

 ?>

Public, private , protected (A.K.A access modifiers)

Public、private、protected(又名访问修饰符)

Before reading the definition below , read this Article about Encapsulation .It will help you to understand the concept more deeply

在阅读下面的定义之前,先阅读这篇关于封装的文章。它会帮助你更深入地理解这个概念

Link 1 wikipedia

链接 1 维基百科

Tutorials point link about encapsulation

关于封装的教程指向链接

Definition

定义

Using private , public , protected keywords you can control access to the members in a class. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

使用 private 、 public 、 protected 关键字可以控制对类中成员的访问。声明为 public 的类成员可以在任何地方访问。声明为 protected 的成员只能在类本身内以及被继承类和父类访问。声明为私有的成员只能由定义该成员的类访问。

Example

例子

 <?php 
class Example{
 public $variable = 'value'; // variable declared as public 
 protected $variable = 'value' //variable declared as protected
 private $variable = 'value'  //variable declared as private

 public function functionName() {  //public function
 //statements
 }

 protected function functionName() {  //protected function
 //statements
 }
  private function functionName() {  //private function
   //statements
   }

} 
 ?> 

Accessing the public, private and protected members example

访问公共、私有和受保护成员示例

Public variable's can be accessed and modified from outside the class or inside the class. But You can access the private and protected variables and functions only from inside the class , You can't modify the value of protected or Public members outside the class.

可以从类外部或类内部访问和修改公共变量。但是您只能从类内部访问私有和受保护的变量和函数,不能在类外部修改受保护或公共成员的值。

  <?php 
  class Example{
    public $pbVariable = 'value'; 
    protected $protVariable = 'value'; 
    private $privVariable = 'value';
    public function publicFun(){

     echo $this->$pbVariable;  //public variable 
     echo $this->$protVariable;  //protected variable
     echo $this->privVariable; //private variable
    }

   private function PrivateFun(){

 //some statements
  }
  protected function ProtectedFun(){

 //some statements
  }

  }


 $inst = new Example();
 $inst->pbVariable = 'AnotherVariable'; //public variable modifed from outside
 echo $inst->pbVariable;   //print the value of the public variable

 $inst->protVariable = 'var'; //you can't do this with protected variable
 echo $inst->privVariable; // This statement won't work , because variable is limited to private

 $inst->publicFun(); // this will print the values inside the function, Because the function is declared as a public function

 $inst->PrivateFun();   //this one won't work (private)
 $inst->ProtectedFun();  //this one won't work as well (protected)

  ?>

For more info read this php documentation about visibility Visibility Php Doc

有关更多信息,请阅读有关可见性 Visibility Php Doc 的 php 文档

References : php.net

参考资料:php.net

I hope you understood the concept. Thanks for reading :) :) Have a good one

我希望你理解这个概念。感谢阅读 :) :) 祝你好运

回答by d.raev

So to recap on @Matt great answer:

所以回顾一下@Matt 很好的答案:

  • if the property you need should not be changed, then a constant is the the proper choice

  • if the property you need is allowed to be changed, use static instead

  • 如果你需要的属性不应该改变,那么常量是正确的选择

  • 如果允许更改您需要的属性,请改用静态

Example:

例子:

class User{
    private static $PASSWORD_SALT = "ASD!@~#asd1";
    ...
}

class Product{
    const INTEREST = 0.10;
    ...
}


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

编辑:重要的是要注意PHP 7.1.0 引入了对指定类常量可见性的支持