Get And Set Method in PHP

In this article I am going to explain get and set magic mathods in PHP
  • 1955

__set() magic method

The __set() is run when writing data to inaccessible properties.

__get() magic method

The __get() magic method reads data from inaccessible properties.

Example

<?php

class
MyClass
{

private
$fname;
private
$lname;
private
$email;

// set user's first name
public
function setFName($fname)
{
$
this->fname = $fname;
}

// get user's first name
public
function getFName()
{

return
$this->fname;
}

// set user's last name
public
function setLName($lname)
{
$
this->lname = $lname;
}

// get user's last name
public
function getLName()
{

return
$this->lname;
}

// set user's email address

public function setEmail($email)

{

$this->email = $email;

}

 

// get user's email address

public function getEmail()

{

return $this->email;

}

}

 

$user = new MyClass();

$user->setFName('Ajeet');

$user->setLName('Dubey');

$user->setEmail('adubey@gamil.com');

echo 'First Name: ' . $user->getFName().' </br>Last Name: ' . $user->getLName() .'</br> Email: ' . $user->getEmail();

?>

Output

magic-methods-in-php.jpg

© 2018 DotNetHeaven. All rights reserved.