pTutorial

New way to learn Programming

PHP 5 __Get() Method

PHP __get Magic Methods

PHP is a loosely coupled programming language, so that you can use variable without declaring it. It is one of the features of a loosely coupled programming language.


In other programming languages you must need to declare the variable before using it.

Example

<?php

class Computer {

public $processer;

}

$c = new Computer();
$h=$c->processer = "Intel Core I3";
$h1=$c->color = "Black";

echo $h." ".$h1;
	  
?>

Output

Intel Core I3 Black

If you run this code it will run properly even assign a value to undefined variable "color".

__get method

To intercept attempts to read an undefined property of any class, you create a method called _get() within your Class to give the response of undefined property.

(Two underscore in font of get) __get() method should expect a single parameter the name of the requested property. It should then return a value this value in turn gets passed back to the calling code as the retrieved property value.

Example __get method

<?php

class Computer 
{
public function __get( $model ) {
echo "The requested $model of the computer 
"; return "Sony Vaio E series"; } } $Computer = new Computer; $a = $Computer-> model; echo "The Computers model is $a
"; ?>

Output

The requested model of the computer
The Computers model is Sony Vaio E series

In the above example, the Computer class contains no actual properties, but it does contain a _get() method. If anyone request any undefined property then it prints the requested property and returns Sony Vaio E series .


QUOTES OF THE DAY

Saying is one thing, and doing is another.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER