2

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;   
    }
5
  • 1
    Can you show the Menu class constructor?
    – al'ein
    Aug 26, 2015 at 18:14
  • The first argument $menuLink takes in a Link object that is used as label for the Menu (using Bootstrap) and the second $menuItems is an array of Link Objects which are later used to display a submenu.
    – Matt
    Aug 26, 2015 at 19:16
  • In Java or C++ I would just create an Array or Vector of type Link, but I'm not sure if PHP supports Type Hinting with Arrays.
    – Matt
    Aug 26, 2015 at 19:18
  • But your error doesn't seem directly connected to type casting. Did you try to var_dump($item) inside the foreach and see what you get?
    – al'ein
    Aug 26, 2015 at 19:22
  • Maybe it can help you.
    – al'ein
    Aug 26, 2015 at 19:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.