Get And Set Method in PHP

Introduction

PHP is a loosely typed language. There is no need to declare variables first to other language for assigning a value. In PHP it is not necessary to declare variables before using them. I am writing an example of that.

<?
php
class
Myclass
public
$val;
$
c = new Customer();
$
c->val = "abc";
$c->email = "[email protected]";

?>

In the another strict language like C#, it would be an error, but in the PHP its ok. So PHP works perfectly with this, and you can assign a value to an undefined variable. Because of this feature PHP provides two magic  __get and __set methods. The purpose of these methods will be to run when you try to access a variable that has not been declared. In PHP __set() is used when a value is to be assigned to an undefined variable of a class and __get() is used when the value from an undefined variable is to be read.

__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


Similar Articles