Page 1 of 1

array to create instances

Posted: Sun Nov 21, 2004 6:03 pm
by John Cartwright

Code: Select all

<?php

	$includes = array('nav','template');
	
	foreach ($includes as $included)
	{
		include('classes/class.'.$included.'.php');
		$included = new $included.'()';
	}

?>
I have several classes I want to include, each on seperate pages.
How can I do something like the following

I get the following error
Fatal error: Call to a member function includepage() on a non-object in C:\apache2triad\htdocs\index_temp.php on line 24

Posted: Sun Nov 21, 2004 6:11 pm
by peni
must depend on your classes and their constructors, probably.
such kind of declaration works fine at my pc:

Code: Select all

$clsName = "myClass";
 $myObj = new $clsName;

Posted: Sun Nov 21, 2004 6:36 pm
by John Cartwright
the problem is that the object name has to be the same..

look at my code above

Posted: Sun Nov 21, 2004 7:04 pm
by timvw
if i understand well:

Code: Select all

foreach($includes as $included)
{
      include('classes/class.'.$included.'.php'););
     $included = new $included;
}
seems to work overhere (PHP5)...

Posted: Sun Nov 21, 2004 7:21 pm
by John Cartwright
im running PHP5.. and according to the late master feyd he sais it will require a singleton becuase I will lose the previous instance each time it is looped.

Posted: Sun Nov 21, 2004 8:48 pm
by crabyars
Could you use the object in an array? then maybe you can do something like this:

Code: Select all

<?php

    $includes = array('nav','template');
    $objArray = array();
    
    foreach ($includes as $included)
    {
        include('classes/class.'.$included.'.php');
        $objArray[] = new $included.'()';
    }

?>
Or, perhaps you need to de-reference the declaration name (see extra $ on line 8):

Code: Select all

<?php

    $includes = array('nav','template');
    
    foreach ($includes as $included)
    {
        include('classes/class.'.$included.'.php');
        $$included = new $included.'()';
    }

?>
With the second example, I imagine you end up with 2 object named $nav and $template