Click here to Skip to main content
15,889,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
sir when we un-comment the getModel method in child class and execute it dispaly error private property can not access in child but in get_Display method same propety is access how is it possible or i m making a mistake?

class Tv{
public $volume;
private $model;

function volume_up(){
$this->volume++;
}


function __construct($m,$v){
$this->model=$m;
$this->volume=$v;
}

function getModel(){
return $this->model;

}

}





$obj=new Tv('xyz',10);
//$obj->model;//error can not access private property

echo $obj->getModel();// can access private property


class Plazma extends Tv {
/*function getModel(){
return $this->model;

}*/


function get_Display( ){
return $this->model='AXN';

}


}

$obj2=new Plazma('xyz',10);
//$obj->model;//error can not access private property

// $obj2->getModel();// can access private property
echo $obj2->get_Display('ANX');
?>

What I have tried:


class Tv{
public $volume;
private $model;

function volume_up(){
$this->volume++;
}


function __construct($m,$v){
$this->model=$m;
$this->volume=$v;
}

function getModel(){
return $this->model;

}

}





$obj=new Tv('xyz',10);
//$obj->model;//error can not access private property

echo $obj->getModel();// can access private property


class Plazma extends Tv {
/*function getModel(){
return $this->model;

}*/


function get_Display( ){
return $this->model='AXN';

}


}

$obj2=new Plazma('xyz',10);
//$obj->model;//error can not access private property

// $obj2->getModel();// can not access private property
echo $obj2->get_Display('ANX'); // but here private property is access why ?
?>
Posted
Updated 11-Aug-16 23:46pm

1 solution

You are not accessing the private property directly, but using a 'getter' to return it from the class. This is the correct way to do it, by calling getModel.
 
Share this answer
 
Comments
[no name] 12-Aug-16 9:56am    
sir ,thanks for solution but there is an issue getModel function working properly,private propery can't be accessed there but in get_Display when i am initilize $this->model='AXN' there should be an error occured private property can not be accessed,but its not happening why?
Richard MacCutchan 12-Aug-16 10:46am    
$this->model='AXN'
No, there should not be an error as that instruction is happening inside the class, which has access to private properties. I do not know PHP, are you sure that instruction is updating the property you are talking about, and not dynamically creating a new one?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900