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)();
繼承