I just started following a video series on OOP in PHP and have made the following class following one lecture. At first there was no __get
and __set
, because he showed us to how to deal with public variables. But for demonstrations sake the lecturer changed public $postal_code
into protected $_postal_code.
Basically what he showed was that he could change the original postal code that we set using
$adress->postal_code = "M422 3555";
into "ADDED PROTECTED VALUE
" via this method
protected function _postal_code_guess(){
return 'ADDED PROTECTED VALUE';
Now the two main things I'm having trouble understanding is how do our __get
and __set
methods know what $name
is? If I echo $name
before anything in either the get or set methods it tells me it represents postal_code
. But why is that? Where is it getting set that value?
The other thing I am a bit confused about is how the line $output.=",".$this->postal_code;
is still working. Because we changed our original public $postal_code
into protected $_postal_code;
Doe-sent that mean we should change
$output.=",".$this->postal_code;
into
$output.=",".$this->_postal_code;
TLDR
1.How does our code know what $name
is ?
- Why are we still allowed to do
$output.=",".$this->postal_code;
, even when our variable was changed toprotected _postal_code
Below is all the code
class Adress{
public $country;
public $province;
public $city;
public $adress;
protected $_postal_code;
// primary key of an adress
protected $_adress_id;
protected $_time_created;
protected $_time_updated;
function __get($name){
if(!$this->_postal_code){
$this->_postal_code = $this->_postal_code_guess();
}
// attempt to return a protected property by name
$protected_property_name = "_".$name;
if(property_exists($this,$protected_property_name)){
return $this->$protected_property_name;
}
trigger_error("Undefined property via __get".$name);
return null;
}
function __set($name,$value){
if('postal_code' == $name){
$this->$name = $value;
return;
}
trigger_error('Undefined or unallowed propert via __set()');
}
protected function _postal_code_guess(){
return 'ADDED PROTECTED VALUE';
}
function display(){
$output = '';
$output.=$this->country;
$output.="<br/>";
$output.=$this->province;
$output.=' '.$this->city;
$output.=" ".$this->adress;
$output.=",".$this->postal_code;
return $output;
}
}
Here is the demo.php file where we run it
<?php
require 'index.php';
$adress = new Adress;
$adress->country = "Canada";
$adress->province = "Ontario";
$adress->city = "Toronto";
$adress->adress ="4324323 Bob Street";
$adress->postal_code = "M422 3555";
echo '<tt><pre>'.var_export($adress,TRUE).'</tt></pre>';
echo $adress->display();
echo '<h2>Test Protected Variables</h2>';
unset($adress->postal_code);
echo $adress->display();