Jump to content
iwato

Class Inclusion and Object Creation

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

Share this post


Link to post
Share on other sites

i think you need this

Share this post


Link to post
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.

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...