[Object-Oriented Bootcamp] 7-Statics-and-Constants

WBOY
Release: 2016-06-23 09:15:08
Original
872 people have browsed it

你可能会在网络上看到一些文章,它提到静态是有害的。他们是什么意思呢?这是真的么?好,这节让我们来谈谈这个。

通过例子学习

改造前,动态调用如下:

<?php class Math{  public function add(){    return array_sum(func_get_args());  }} $math = new Math; var_dump($math->add(1, 2, 3)); //结果int(6) 
Copy after login

从原始动态改造后,静态调用如下:

<?php class Math{  public static function add(...$nums){ //静态方法    return array_sum($nums);  }} var_dump(Math::add(1, 2, 3, 4)); //结果int(10) 
Copy after login

改造为静态方法后,直接用类名调用即可。

再来个例子

静态变量的使用:

<?php class Person {   public static $age = 1;   public function haveBirthday(){    static::$age += 1;  }} $joe = new Person();$joe->haveBirthday();$joe->haveBirthday(); $jane = new Person();$jane->haveBirthday(); echoPerson::$age; //非2,结果为4。$age变量为静态,共享。 
Copy after login

const 标识符:

<?php class BankAccount {  // const标识不改变的值,用大写字符表示 ;类似 private static  const TAX = 0.09; } echoBankAccount::TAX; 
Copy after login

Laravel中使用

Illuminate\Support 中 Str 类大量使用了 static 静态变量和静态方法,例如:

echoStr::lower("FOOBAR"); //结果:foobarechoStr::camel(); 
Copy after login

参考链接:

* PHP5: const vs static

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template