openfrog
openfrog

Reputation: 40735

Is there something like a macro in PHP? Or: How to make an own include function?

What I want to do is this:

When I write a class and the class instantiates another class, I want to import that class with an require_once. Just the way I do so in Objective-C. But instead of using plain require_once function and messing around with paths and string concatenation, I would prefer something like:

importClass('myclass');

but I'm afraid that it's impossible to write a function that will include code. If I would do that in the importClass() function, I would include the class code into the implementation block of the function, which of course is nonsense. So what options do I have here?

Upvotes: 2

Views: 1863

Answers (4)

cletus
cletus

Reputation: 625097

It's not impossible at all. You can write this function:

function importClass($class) {
  require_once "$class.class.php";
}

The only caveat is that any global variables declared or used inside that file will now be local to importClass(). Class definitions however will be global.

I'm not sure what this really gives you however but you can certainly do it.

Upvotes: 4

pix0r
pix0r

Reputation: 31280

You can accomplish something similar using a class autoloader. I would also make sure that your include_path is set properly and that you are using a directory structure that makes sense for your classes - it's generally a good practice to NOT depend on class autoloaders, and instead include classes based on their relative path to your include_path.

I'd highly recommend browsing through Zend Framework, particularly Zend_Loader, for a good (if not over-architected) implementation. Also notice that Zend Framework will work without an autoloader in place - each file calls require_once on its direct dependencies, using their nice, organized directory structure.

Upvotes: 1

Carson Myers
Carson Myers

Reputation: 38564

In my application I have a system base class which has a similar function. The import function takes a class name, looks in a couple of related directories and finds a matching name (I also did some stuff with extensions to libraries but you may not need that) and instantiates a class inside with the same name. Then it takes that new instance and sets it as an object in the system base class.

using autoload as other answers have suggested would probably work better in your situation but this is just another way to look at it.

Upvotes: 1

Yacoby
Yacoby

Reputation: 55445

The cleanest way to do what you want looks to be to use the Autoloader

Upvotes: 8

Related Questions