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
- why cant assign value to protected property in code block 2
- why cant assign value to public property using protected method in code block 3
- why construct cant be protected in code block 4
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 toecho
the variable from the outside.The same goes for the method in Block 3.
The Constuctor can be
protected
or evenprivate
. But you cannot call it from the outside anymore. But something like this is possible: