I am currently working on an API in PHP for my personal use and have created a design that relies heavily on the ability to tap into polymorphism. I frequently work with languages like C++, Java and Objective-C where polymorphism has more versatility.
I have noticed that PHP is a little more resistant to polymorphism and was wondering if someone knows the proper syntax for what I am attempting below:
// FIRST Create objects and store in variables
$link0 = new Link("#", "StackOverflow");
$link1 = new Link("http://www.stackoverflow.com", "StackOverflow");
$link2 = new Link("http://www.stackcareers.com", "StackCareers");
// Use
$stack_submenu = new Menu( $link0, array( $link1,$link2 ) );
...
foreach ( $stack_submenu->menuItems as $item ) {
$item->html();
}
The above example gives me the follow error:
Fatal Error - Call to a member function html() on a non-object
I read around and found a way to drop the error by changing the syntax, however, I MUST call the constructors to the Link Objects inside the array:
// WORKS, but does not allow me to use variables in place of constructor
$submenu_mamp = new Menu($link_mamp, array( new Link("http://www.stackoverflow.com", "StackOverflow"), new Link("http://www.stackcareers.com", "StackCareers")));
The above works, but for the sake of my application, I construct the objects before constructing the array. I have tried passing by reference, but I get the same error stated earlier.
Is there anyway to do what I am trying, or do I have to directly call the constructor inside the array definition?
EDIT
Menu Class Constructor:
// CONSTRUCTOR
public function __construct($menuLink, $menuItems) {
// Set Properties
$this->menuLink = $menuLink;
$this->menuItems = $menuItems;
}