array to create instances

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

array to create instances

Post 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
peni
Forum Commoner
Posts: 34
Joined: Thu Nov 18, 2004 1:15 pm

Post 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;
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

the problem is that the object name has to be the same..

look at my code above
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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)...
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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.
crabyars
Forum Commoner
Posts: 37
Joined: Thu Jun 17, 2004 8:24 pm

Post 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
Post Reply