php my way.md

php the right way

參考php the right way

代碼環境

mac OS Homebrew
PHP 5.6.20 (cli)
nginx version: nginx/1.8.1
mysql Ver 14.14 Distrib 5.7.12, for osx10.11 (x86_64) using EditLine wrapper

代碼風格

閱讀 PSR-0
閱讀 PSR-1
閱讀 PSR-2
閱讀 PSR-4
閱讀 PEAR 編碼準則
閱讀 Symfony 編碼準則
使用PHP_CodeSniffer 檢查代碼是否符合規范
使用 PHP Coding Standards Fixer自動修復語法格式

面向對象

簡單類

class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
$a = new SimpleClass();
$b = new SimpleClass();

類是對象的模板,實例化一個類就是使用模板生產一個實際對象

$this

指向這個類的當前對象

error_reporting(false);
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined ('.get_class($this).")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}
class B
{
    function bar()
    {
        A::foo();
    }
}
$a = new A();
$a->foo();  // $this is defined (A)
A::foo(); //$this is not defined.

$b = new B(); 
$b->bar(); // //$this is defined (B)
B::bar(); // $this is not defined.

new 變量名(帶命名空間)

$className = 'SimpleClass';
$instance = new $className(); // 等同于 new SimpleClass()

變量賦值與引用

$instance = new SimpleClass();
$assigned   =  $instance;
$reference  = &$instance;
$instance -> var = '$assigned will have this value';
$instance = null; // $instance and $reference become null

var_dump($instance); // null
var_dump($reference); // null
var_dump($assigned); //object(SimpleClass) 1 (1) { ["var"]=>string(30) "$assigned will have this value"}

創建對象的幾種方式

class Test
{
    static public function getNew()
    {
        return new static; // new static 是返回當前對象模板實例化的變量,
    }
}
class Child extends Test  // 繼承
{}
$obj1 = new Test();
$obj2 = new $obj1; // 通過new對象實例來創建一個該類的新對象
var_dump($obj1 !== $obj2); // true

$obj3 = Test::getNew();
var_dump($obj3 instanceof Test); // true

$obj4 = Child::getNew();
var_dump($obj4 instanceof Child); // true

匿名函數

class Foo
{
    public $bar;

    public function __construct() {
        $this->bar = function() {
            return 42;
        };
    }
}

$obj = new Foo();

// as of PHP 5.3.0:
$func = $obj->bar;
echo $func() , PHP_EOL;

// alternatively, as of PHP 7.0.0:
// echo ($obj->bar)();

繼承



最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Composer Repositories Composer源 Firegento - Magento模塊Comp...
    零一間閱讀 3,969評論 1 66
  • ziadoz在 Github發起維護的一個PHP資源列表,內容包括:庫、框架、模板、安全、代碼分析、日志、第三方庫...
    Gundy_閱讀 6,354評論 4 192
  • Welcome 目前網絡上充斥著大量的陳舊信息,讓PHP新手誤入歧途,傳播著錯誤的實踐和糟糕的代碼,這必須得到糾正...
    layjoy閱讀 21,724評論 7 118
  • 我相信人與人之間能認識是緣份,深淺,長久,珍不珍惜看個人。 這件事情已經過去了一周了,我還是會常常想起,有一些自責...
    堅持成習慣閱讀 210評論 2 1
  • 十點,洗完澡一身輕,又是周六,光想想,都覺得沒那么疲憊了。對著鏡子,習慣性撩撥幾下左右兩邊的頭發,一下子危機感又涌...
    小樹乘涼閱讀 301評論 0 0