SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member wisskid's Avatar
    Join Date
    May 2004
    Location
    Groningen, the Netherlands
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Lightbulb Implementing Interfaces in PHP4

    This is just a tip to show how you can 'fake' interfaces in PHP4. Ofcourse this will all be useless after switching to PHP5, but for the time being this might help you out. Furthermore, I've tried to set it up so you can do an easy search-and-replace on your code when you switch to PHP5.

    Code:
    class IPrintable {
    
    	// should render to screen
    	function printme() {}
    
    }
    
    class Page {
    
    	function Page() {
    		assert_implements($this, "IPrintable");
    	}
    
    	// implement the printme method
    	function printme() {
    		echo "This is a printed page.<BR/>";
    	}
    
    }
    
    
    class Publisher {
    
    	function Publish(&$printableObject) {
    		assert_implements($printableObject, "IPrintable");
    		$printableObject->printme();
    		return true;
    	}
    
    }
    
    function assert_implements(&$obj, $interfaceName) {
    	if (!class_exists($interfaceName)) {
    	    echo "Interface {$interfaceName} is undefined."; die;
    	}
    	
    	if (!is_object($obj)) {
    		echo "The variable passed to assert_implements is not an object. A var_dump of the variable follows: ";
    		var_dump($obj);
    		die;    
    	}
    	
    	$requiredMethods = get_class_methods($interfaceName);
    	foreach ($requiredMethods as $method_name) {
    		if (!method_exists($obj, $method_name)) {
    			$errClass = get_class($obj);
    		    echo "Interface {$interfaceName} declares the method {$method_name}, which is undefined in class {$errClass}."; die;
    		}
    	}
    }
    
    $page =& new Page();
    $publisher =& new Publisher();
    $publisher->Publish($page);
    Last edited by wisskid; May 26, 2004 at 08:27.

  2. #2
    Non-Member
    Join Date
    Jan 2004
    Location
    Planet Earth
    Posts
    1,764
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    One thing that is surely going to knock me flat on my **** is Interfaces, Abstract class(es) etc that is new with PHPversion 5

    Not from an educated background you understand, this idea of yours though looks interesting all the same


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •