php oop protected property, protected method, prot

2019-09-24 18:28发布

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

can somebody explain why these

  1. why cant assign value to protected property in code block 2
  2. why cant assign value to public property using protected method in code block 3
  3. why construct cant be protected in code block 4

标签: php oop
1条回答
forever°为你锁心
2楼-- · 2019-09-24 18:56

This is the purpose of Visibility.

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.

The same goes for the method in Block 3.

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();
查看更多
登录 后发表回答