access to private properties or methods in class

March 4th, 2016 by Nov Piseth Leave a reply »

This is the code instructed about how to access private properties by methong set and get (it is not related to magic method)

  • date_default_timezone_set(“Asia/Phnom_Penh”); it is php function to let us change our php time to our location time zone. example we are in Phnom Penh, Cambodia so we just this.
  • we have class Student and we have declared seven private properties. in case we want to set value to each properties we need to clear one method that received value from out (short example is setID($id)) after that if we want to get value of the properties at outside class we need to create the method get ( short example is getID().
    please have to check below example code for detail.
class Student {

private $id;
private $firstname;
private $lastname;
private $gender;
private $age;
private $dat;
private $classes;

function Student($classes){
$this->classes = "PHP OOP and Codeigniter";
$this->dat = date("d-m-Y h:i:s");

function getDate(){
return $this->dat;

function getClasses(){
return $this->classes;

function setId($id){
return $this;

function getId() {
return $this->id;

function setFirstname($fname){
$this->firstname = $fname;
return $this;
function getFirstname(){
return $this->firstname;

function setLasttname($lname){
$this->lastname = $lname;
return $this;
function getLastname(){
return $this->lastname;

function setGender($gender){
$this->gender = $gender;
return $this;
function getGender(){
return $this->gender;

function setAge($age){
$this->age = $age;
return $this;
function getAge(){
return $this->age;
function getFullname(){
return $this->firstname." ".$this->lastname;


$obj = new Student();
echo $obj->setId("5678")->getID()."<br />";
echo $obj->getFullname()."<br />";
echo $obj->setGender("Male")->getGender()."<br />";
echo $obj->setAge("35")->getAge()."<br />";
echo $obj->getClasses()."<br />";
echo $obj->getDate();


Comments are closed.

WP2Social Auto Publish Powered By :