5 PHP中静态关键字的5个用法
5 PHP中静态关键字的5个用法

5 PHP中静态关键字的5个用法

静态是具有许多用法的PHP关键字。它几乎普遍使用,尽管它有许多变化。让’S审查其中五个:

  • 静态方法
  • 静态财产
  • 静电关闭
  • 静态变量
  • 静态作为类名

静态方法

静态最常见的使用是用于定义 静态方法.

Such methods are part of a class, just like any method, though they may be used even without any such instantiated object. This is actually the main difference with a normal method : $this is not available in such methods.

<?php 
  class Foo { 
    public static function aStaticMethod() { 
      $var = 'this'; 
      var_dump($$var);   
    } 
    
    public function aNonStaticMethod() { 
      var_dump($this); 
    } 
} 

Foo::aStaticMethod(); 
$object = new foo(); 
$object-> aNonStaticMethod();
?>

Note that static methods may be called from an object, though the pseudo-variable $this will still NOT be available. In fact, PHP emits a fatal error, whenever the $this variable is directly mentioned in a static method : this is why the example has to use the variable variable to actually show the status.

由于静态方法不依赖于物体,因此它们非常适合工厂。它们也很有用来访问私有静态属性,因为它们都是静态的。最后,它们对与类相关但不依赖于本地对象状态的实用程序也是有用的:但是,这些可以被视为函数。

静态属性

静态属性 是静态方法的关闭表兄弟。他们不依赖于物体,而是只在课堂上。他们可能会对该类持有一些重要信息,但不是对象。

静态属性有几个利基使用。其中的第一个是静态方法的属性。这是有道理的:任何静态方法必须存储必须处于静态属性。实际上,私人一个或保护。

They play the role of constants when the value of the constant is dynamically loaded, and thus, are not known at compile time. Non-class constants may be defined at execution time with define, but not class constants : thus, the usage of static properties. They also replace constants when the constant has to be a resource or an array or another object.

当对象实例化具有先决条件时,它们在实现单例时使用它们,或者在对象之间共享数据,例如计数器。它们也可用于本地缓存。

<?php 
  class Foo { 
    private $total = 0; 
    private $count = 0; 
    
    // getter for current count 
    public static function getCount() { 
      return self::$count; 
    } 

   // increment count and total 
   public function __construct() { 
     ++self::$total; ++self::$count; 
   } 
   // decrement count public 
   function __destruct() { 
     --self::$count; 
   } 
} 
?>

静态属性往往难以初始化:可以在编码时间(默认值)或构造时间来初始化所有属性。显然,后者不适用于静态属性,只有默认值也是可能的。另一个选项是在引导程序中设置主代码中的静态属性,导致一些难以解决依赖项。

静电关闭

虽然方法可能是静态的,但功能没有这样的替代方案:他们只是可以’t是静态的。然而,有一种最终类型的方法可能是静态的: 静电关闭.

Closure are functions that may be stored in a variable : functions may have their name stored in a variable, though. Closure also have the ability to aggregate variables from the context of their creation, for future use. As such, $this is available in a closure that is created inside an object.

<?php 
class x { 
  private $y = 1; 
  function foo() { 
    return function() { 
      var_dump($this); 
    }; 
  } 
} 

$object = new x; $f = $object->foo();
$f();

/*
object(x)#1 (1) {
  ["y":"x":private]=>
  int(1)
}
*/

?>

请注意,没有必要‘use ($this)’ when creating the closure to include $this in it : it is automatically done.

Now, if the foo method is actually static, then $this is not available anymore, nor for the static method, nor for the created closure.

但如果你不’t want to propagate the context of creation with the closure, you may actually make the closure 静态的 and $this won’t be available anymore. This may avoid leaks, or will allow the $this variable to be filled by another context later.

<?php class x { 
  private $y = 1; 
  function foo() { 
    return static function() { 
      var_dump($this); 
    }; 
  } 
} 

$object = new x; 
$f = $object->foo();
$f();

/*
Fatal error: Uncaught Error: Using $this when not in object
*/

?>

静态变量

就像有静态方法和静态函数一样,静态属性和 静态变量.

静态变量是保持在上下文中的变量,可在下次调用。

<?php 
  function foo() { 
    static $i = 0; 
    echo $i++; 
}
foo(); 
foo(); 
foo(); 
foo(); 
// 0123 
?>

这实际上实际上是一些史前类:静态变量可用于存储一些缓存的数据:这里,我们用它用作计数器,但静态变量对于任何字典都有很大的缓存’t均加载每个呼叫。在第一个调用中加载字典,然后它将驻留在内存中为其余的执行。

请注意,变量完全从外部世界完全看不起,就像私有财产一样。

通常,静态变量是第一步,然后是完整类:一旦您了解测试此类不可访问的变量需要一些‘reset’机制,其史前魅力WAN和该功能被重构为班级。

静态作为类名

It is not possible to call a class 静态的 but it is well possible to refer to it with this keyword. Within a class body, you may refer to the current class, or any of its parent in case of fallback, using 静态的. That is convenient in a surprising number of situations.

<?php 
  // This code makes no sense : it is just for illustration. 
   class x { 
      static $p = 1; 

     // for typehinting, static is not possible but self is
     function foo(self $x) { 
    // for instantiation 
    $o = new static( ); 
    // for calling oneself statically 
    static::$x = static::foo(); 
    
    // for instanceof 
    return $o instanceof static; 
   } 
} 
?>

When using static in those situations, 静态的 will be dynamically replaced by the current acting class. In the example, it is the x class. When you change the name of the class from x to something else, the rest of the class keeps running : 静态的 acts as a relative class name (relative to the code location, that is).

There is another keyword in competition with 静态的 : it’s self. Together, they handle the 晚期静态绑定.

Basically, self may just be used at the same location, and it will behave almost identically. Except that self is resolved at compile type, ‘statically’ if you pardon the pun, and it will always reference the class it is written in. While 静态的 depends on who is calling the static entity.

使困惑 ?

<?php 
  // This code makes no sense : it is just for illustration. 
  class x { 
     const NAME = 'X'; 
     static function whoAmI() { 
        print static::NAME.PHP_EOL; 
        print self::NAME.PHP_EOL; 
     } 
} 

class y extends x { 
   const NAME = 'Y'; 
} 

// calling as X 
x::whoami(); 
// display X X 

// calling as Y 
y::whoami(); 
// display Y X 

?>

On the first call to whoami(), the context of calling is X, so the method displays X X. On the second call to whoami(), Y is used, but whoami is actually located in X, as Y has no such method. There, 静态的 and self parts ways, and display different classes.

In terms of performances, always default to self, as it will be compiled, and executed as such. 静态的 is far rarely used.

通过静态分析查看您的代码

Static analysis has no relation with the 静态的 keyword. Yet, it may very wel help you review your code, and find usage of those features.

  • 静态方法: 避免使用 $this 在这些方法中,并考虑将静态添加到NON的方法中’t use this variable.
  • 静态财产: 制作 静态的 private,当属性仅在内部使用时。
  • 静电关闭 : add 静态的 when the closure has no usage of the $this.
  • 静态变量 : when the 静态的 variable is not taught, it is often 建立 global that is restricted to one function. Spot those, and make them 静态的 or turn the whole code into a class.
  • 静态作为类名 : whenever the current class is mentioned within itself, think about using self or 静态的 for added comfort.

One thought on “5 PHP中静态关键字的5个用法

  1. pingback: exakat博客:PHP中的静态关键字的5个用法 - WebDev.am

评论被关闭。