Jump to content

Class Inclusion and Object Creation


iwato

Recommended Posts

Question: I have created a class in one PHP file and wish to create an object from that class in another PHP file. Is there a way to make a call to the class's __construct() method without having to include the entire file in which the class is located?Roddy

Link to comment
Share on other sites

Of course you have to include the file that contains the class. Otherwise the program has no idea what your class is or what it contains.If your class file contains a whole lot of other things then you might want to consider putting the class in its own file.

Link to comment
Share on other sites

i think you need this
As Ingolme suggests this does not eliminate the need for the include statement, but with the following block of code it surely makes life easier. Great link! Thanks.The expression './[path_to]../classes/' is a user's path pointing to a folder called "classes". Each class is contained in a separate file whose name is the name of the class and whose extension is .class. SomeClassName refers to the name of the file that contains the class that you wish to access.I have tried it and it works really well.
<?php	$classPath  = realpath('./[path_to]../classes/');	echo set_include_path(get_include_path().PATH_SEPARATOR.$classPath);		function __autoload($class_name) {		$include_path = get_include_path();		$include_path_tokens = explode(':', $include_path);			foreach($include_path_tokens as $prefix){			echo $path = $prefix . '/' . $class_name . '.class';			if(file_exists($path)){				require_once $path;				return;			}		} 	}?>

<?php	 $myNewClassObject = new SomeClassName();	 $myNewClassObject->someProperty;	 $myNewClassObject->someMethod;?>

Roddy

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...