2015-11-18 68 views
-2

這些是我已經寫PHP接力保護屬性,保護方法,保護的構建體

<?php 
/**************** code block 1 *****************/ 
class Database1 
{ 
    public $rows; 

    public function __construct() 
    { 

    } 

    public function assingrow() 
    { 
     $this->rows=5; 
    } 
} 


$database1 = new Database1(); 
$database1->assingrow(); 
echo $database1->rows; 

//no error 




/**************** code block 2 *****************/ 
class Database2 
{ 
    protected $rows;// 

    public function __construct() 
    { 

    } 

    public function assingrow() 
    { 
     $this->rows=5; 
    } 
} 


$database2 = new Database2(); 
$database2->assingrow(); 
echo $database2->rows; 
//error message 
//Fatal error: Cannot access protected property Database2::$rows in E:\xampp\htdocs\pdo\4.php on line 46 





/**************** code block 3 *****************/ 
class Database3 
{ 
    public $rows; 

    public function __construct() 
    { 

    } 

    protected function assingrow()//// 
    { 
     $this->rows=5; 
    } 
} 


$database3 = new Database3(); 
$database3->assingrow(); 
echo $database3->rows; 
//error message 
//Fatal error: Call to protected method Database3::assingrow() from context '' in E:\xampp\htdocs\pdo\4.php on line 68 





/**************** code block 4 *****************/ 
class Database4 
{ 
    public $rows; 

    protected function __construct() 
    { 

    } 

    public function assingrow() 
    { 
     $this->rows=5; 
    } 
} 


$database4 = new Database4(); 
$database4->assingrow(); 
echo $database4->rows; 
//error message 
//Fatal error: Call to protected Database4::__construct() from invalid context in E:\xampp\htdocs\pdo\4.php on line 91 

可有人解釋一些示例代碼爲什麼這些

  1. 爲什麼不能將值分配給受保護的場所在碼塊2
  2. 爲什麼不能將值分配給公共屬性使用受保護的方法中的代碼塊3
  3. 爲什麼構建體傾斜在碼塊被保護的4-
+1

請閱讀[文檔](http://php.net/manual/en/language.oop5.visibility.php),如果你之後有問題,請寫它 –

回答

1

這是Visibility的用途。

在第2區你的房產是protected。這意味着它只能訪問類本身(Database2)和繼承類。當您嘗試從外部變量echo時發生錯誤。

這同樣適用於所述方法中塊3

的Constuctor可以protected甚至private。但你不能從外面打電話給它。但是,這樣的事情是可能的:

class Foo 
{ 
    private function __construct() 
    { 
    } 

    public static function create() 
    { 
     return new self(); 
    } 
} 

$foo = Foo::create();