Creating Set Get magic method

Simple Set Get magic method, which will set and get values. Without passing the arguments into the function.
We will create new class call push, which will have setData and getData function.

<?php
class push {
	public $result = '';
	
	function setData() {
		$this->result .= ' to codeasearch.com '.date("Y-m-d");
	}
	
	function getData() {
		echo $this->result;
	}	

Creating magic method function __set and __get

// writing the data using __set magic method
	function __set($name,$value) {
		$this->result = $value;
		$this->$name();
	}	
	
	// reading the data using __get magic method
	function __get($name) {
		$this->$name();
	}	
}


Creating object for the class push and setting and getting values.

// creating the object 
$obj = new push;

// setting the value
$obj->setData = 'Welcome ';

// getting the data
$obj->getData;

[ Download ] | [ Demo ]
Share