这些是我编写的一些示例代码
<?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
有人可以解释为什么这些
答案 0 :(得分: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();