Mar 27

A very efficient way of instantiating a class dynamically in PHP


Since PHP is a loosely typed language, it provides great flexibility in creating variables and objects at runtime without having to specifically declare them first. It is well known that $i=10, $i=”test”, $i = date() will all work without creating any syntax or compile errors.

A lesser used concept is that this feature can be used to create an object at runtime without having to check for the object type at first. Eg.if you have had 3 classes and only one of them had to be created depending on a condition the following would be the sample code:

<?php
	error_reporting(E_ALL);

	class Generic {
		function xprint() {
			echo("generic");
		}
	}
	class A extends Generic{
		function xprint() {
			echo("A");
		}
	}

	class B extends Generic{
		function xprint() {
			echo ("B");
		}
	}

	class C extends Generic{
		function xprint() {
			echo("C");
		}
	}

	$test = "B";
	if ($test =="B")
		$x = new B();
	else if ($test == "A"
		$x = new A();
    else if ($test == "C")
	    $x = new C();
	$x->xprint();
	echo("end");
?>

Instead of doing multiple checks and then creating the relevant class, a more efficient way is to pass the classname as a string and then create it directly as shown below:

<?php
	error_reporting(E_ALL);

	class Generic {
		function xprint() {
			echo("generic");
		}
	}
	class A extends Generic{
		function xprint() {
			echo("A");
		}
	}

	class B extends Generic{
		function xprint() {
			echo ("B");
		}
	}

	class C extends Generic{
		function xprint() {
			echo("C");
		}
	}

	$test = "B";
	$x = new $test();
	$x->xprint();
	echo("end");
?>

The above code will print “B” since it creates the class B in $x. What about classes where arguments are required in the constructor? Simple call it with the arguments eg. $x = new $test(“arg1″, “arg2″);

Mar 18

Linked List class in Javascript


ThisĀ  is an exercise in using the object oriented concepts in Javascript to implement a doubly linked list.

There is a class called Node which encapsulates the actual node in the list. The linked list is implemented as a global object with class variables and methods to:

  • Add a node
  • Remove a node
  • Search for a node
  • Sort the list in ascending order
  • Display the entire list

The Node object simply stores a string. There is scope for further improvement, as always. The source is easily available by viewing the page source. Any comments and recommendations for changes or improvements are welcome.

You can see the implementation here