PROWAREtech

articles » current » php » tips-and-tricks » page-3

PHP: Tips and Tricks - Page 3

Variables, functions and classes.

Variables

Dynamic Variable Names

Use the variable variable syntax by prepending a $ to a variable whose value us the variable name you want.

<?php
	$dynamic = 'number';
	$number = 1024;
	print $$dynamic; // prints 1024!
	print ' ';
	print "${'num'.'ber'}"; // prints 1024!
?>

Serialize Data Using JSON

Use the functions json_encode and json_decode to serialize arrays.

<?php
	$arr = array('first_name' => 'John', 'last_name' => 'Smith', 'age' => 25, 'address' => array('street' => '123 Abc Ln', 'city' => 'New York', 'state' => 'NY'));
	$json = json_encode($arr);
	$f = fopen('personal_info.json', 'w') or die('cannot open personal_info.json');
	fputs($f, $json);
	fclose($f) or die('cannot close personal_info.json');
	print $json;
?>
<?php
	$arr = json_decode(file_get_contents('personal_info.json'), TRUE);
	print '<pre>';
	print_r($arr);
	print '</pre>';
?>

Functions

Dynamic Functions

Define a function dynamically as the script is running.

<?php
	$x = 10;
	$volume = function($y, $z) use ($x) {
		return $x * $y * $z;
	};
	$v = $volume(5, 7);
	print $v;
?>

Variable Number of Arguments

Pass the function a single array-typed argument and put the variable arguments in the array.

<?php
	function html_bold($items) {
		$html = '';
		foreach($items as $i) {
			$html .= '<b>'.$i.'</b>';
		}
		return $html;
	}
	$arr = array('this', 'is', 'a', 'test');
	$str = html_bold($arr);
	print $str;
?>

Return Values by Reference

To return by reference place a & symbol before the name of the function. Also, use the =& operator when invoking the function.

<?php
	function &find_array_value(&$array, $search_value) {
		foreach($array as $key => $value) {
			if($search_value == $value) {
				return $array[$key];
			}
		}
	}
	$arr = array('this', 'is', 'a', 'test');
	$f =& find_array_value($arr, 'test');
	print $f;
?>

Accessing a Global Variable

Global variables can be brought into scope using the global keyword.

<?php
	function some_func() {
		global $some_var;
		$some_var++;
	}
?>

Or:

<?php
	function some_func() {
		$GLOBALS['some_var']++;
	}
?>

Classes

Access Modifiers

Use the private, protected and public keywords to control access to methods and data members.

<?php
	class Food {
		private $pasta; // available only to this class
		protected $apples; // available to this class and derived classes
		public $nuts; // available everywhere

		private function set_apples() {
			$this->apples = 4;
		}

		protected function set_nuts() {
			$this->nuts = 100;
		}

		public function set_pasta() {
			$this->pasta = 1;
		}
	}

	class Dinner extends Food {
		private $guests;

		public function set_apples() {
			$this->apples = 2; // can access the protected member of the base class
		}

		public function set_guests() {
			$this->guests = 4;
		}

		public function set_food() {
			$this->set_nuts();
		}
	}

	$f = new Food;
	$f->set_pasta(); // the only method that can be called from outside the Food class
	$f->nuts = 50; // the only member that can be accessed from outside the Food class
	$d = new Dinner;
	$d->set_apples(); // changes the apples member of the base class
	$d->nuts = 75; // can access the nuts member of the base class
	$d->set_pasta(); // can access set_pasta method of the base class
?>

Static Methods

Access methods without instantiating an object.

<?php
	class Rectangle {
		public static function area($width, $height) {
			return $width * $height;
		}
	}

	$area = Rectangle::area(65, 33);
	print $area;
?>

Abstract Base Classes

Create a class that is not directly instantiable but is a common base class for derived classes. Use the abstract keyword.

<?php
	abstract class TwoDimensional {
		abstract public function set_width($value);
		abstract public function set_height($value);
	}

	class Rectangle extends TwoDimensional {
		private $width;
		private $height;

		public function set_width($value) {
			$this->width = $value;
		}

		public function set_height($value) {
			$this->height = $value;
		}
	}
?>

Interfaces

Interaces require that classes behave in a similarly fashion. Define an interface and declare that a class implements it.

<?php
	interface RectangleInterface {
		public function set_width($value);
		public function set_height($value);
	}

	class Rectangle implements RectangleInterface {
		private $width;
		private $height;

		public function set_width($value) {
			$this->width = $value;
		}

		public function set_height($value) {
			$this->height = $value;
		}
	}
?>

Cloning Objects

When the assignment operator (=) is used with objects, it copies by reference. To copy objects by value use clone.

<?php
	class Rectangle {
		private $width;
		private $height;

		public function set_width($value) {
			$this->width = $value;
		}

		public function set_height($value) {
			$this->height = $value;
		}
	}
	$rect1 = new Rectangle;
	$rect2 = $rect1 // $rect2 points to $rect1
	$rect3 = clone $rect1; // now there are two objects
?>

Class Constants

Use const and self keywords and ::.

<?php
	class Circle {
		const pi = 3.14159;
		protected $radius;

		public function set_radius($value) {
			$this->radius = $value;
		}

		public function circumference() {
			return 2 * self::pi * $this->radius;
		}
	}
	$radius = 10;
	$area = Circle::pi * $radius * $radius;
	print $area;
	$circle = new Circle;
	$circle->set_radius(25);
	print $circle->circumference();
?>

Accessing Overridden Methods

To access a method in the base class that's overridden by the derived class, use the parent keyword.

<?php
	class Rectangle {
		protected $width;
		protected $height;

		public function set_width($value) {
			$this->width = $value;
		}

		public function set_height($value) {
			$this->height = $value;
		}

		public function area() {
			return $this->width * $this->height;
		}
	}

	class Box extends Rectangle {
		protected $depth;

		public function set_depth($value) {
			$this->depth = $value;
		}

		public function area() {
			if($this->width == $this->height && $this->width == $this->depth) {
				return parent::area() * 6; // use parent to refer to the base class
			}
		}
	}
?>

Object Stringification

Control how objects are displayed. Implement a __toString() method.

<?php
	class Rectangle {
		private $width;
		private $height;

		public function __toString() {
			return $this->width.'x'.$this->height;
		}

		public function set_width($value) {
			$this->width = $value;
		}

		public function set_height($value) {
			$this->height = $value;
		}
	}
?>

Check Which Class an Object is an Instance of

Use the instanceof keyword.

<?php
	class Rectangle {
		private $width;
		private $height;

		public function set_width($value) {
			$this->width = $value;
		}

		public function set_height($value) {
			$this->height = $value;
		}
	}
	$rect = new Rectangle;
	if($rect instanceof Rectangle) {
		print '$rect is a Rectangle';
	}
?>

Dynamic Object Instantiation

<?php
	class Rectangle {
		private $width;
		private $height;

		public function set_width($value) {
			$this->width = $value;
		}

		public function set_height($value) {
			$this->height = $value;
		}
	}
	$class_name = 'Rectangle';
	$class = new $class_name; // new Rectangle
	if($class instanceof Rectangle) {
		print '$class is a Rectangle';
	}
?>

Automatically Load Class Files when Instantiated

There is no reason to include all the class definitions in every script so use the __autoload function include only the class definitions used by the script.

<?php
	function __autoload($class_name) {
		include "$class_name.php";
	}
	$rect = new Rectangle; // this is when the Rectangle.php file will be included.
?>
<<<[Page 3 of 6]>>>

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT