iwato Posted February 25, 2011 Share Posted February 25, 2011 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 More sharing options...
birbal Posted February 25, 2011 Share Posted February 25, 2011 i think you need this Link to comment Share on other sites More sharing options...
Ingolme Posted February 25, 2011 Share Posted February 25, 2011 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 More sharing options...
Zilee Posted February 27, 2011 Share Posted February 27, 2011 You always have to include the whole .php, only other option I see is _autoload:http://php.net/manual/en/language.oop5.autoload.phpEnjoy. Link to comment Share on other sites More sharing options...
iwato Posted February 28, 2011 Author Share Posted February 28, 2011 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 More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.