php oop 受保护的属性、受保护的方法、受保护的构造 [英] php oop protected property, protected method, protected construct
本文介绍了php oop 受保护的属性、受保护的方法、受保护的构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这些是我写的一些示例代码
these are some example code I have written
<?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
谁能解释为什么这些
- 为什么不能在代码块 2 中为受保护的属性赋值
- 为什么不能在代码块 3 中使用受保护的方法为公共属性赋值
- 为什么不能在代码块 4 中保护构造
推荐答案
这是可见性.
在第 2 块中,您的财产受到保护
.这意味着它只能被类本身(Database2
)和继承的类访问.当您尝试从外部 echo
变量时发生错误.
In Block 2 your property is protected
. This means it can only be accessed the class itself (Database2
) and by inherited classes. The error occurs when you try to echo
the variable from the outside.
同样适用于 Block 3 中的方法.
The same goes for the method in Block 3.
构造函数可以被protected
甚至private
.但是你不能再从外面调用它了.但这样的事情是可能的:
The Constuctor can be protected
or even private
. But you cannot call it from the outside anymore. But something like this is possible:
class Foo
{
private function __construct()
{
}
public static function create()
{
return new self();
}
}
$foo = Foo::create();
这篇关于php oop 受保护的属性、受保护的方法、受保护的构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文