Matt
Matt

Reputation: 22921

Abstract a class away from PHP script?

Just wondering if there is anyway to have PHP just run a certain class given the name of the file (controller.php)?

I don't want to require, include or see any signs of it in the controller.php. I just want it to be there.

EDIT: Ok. What I mean by run is in some file hidden away from me I say something like... $class = new Class(); This way I can use $class in my controller.php

ALSO: I'm running PHP 5.3 - So I have namespaces and whatnot.

Anyway of doing this??

Thanks! Matt Mueller

Upvotes: 0

Views: 110

Answers (2)

Joseph Mansfield
Joseph Mansfield

Reputation: 110698

I'm going to take a big guess at what you really mean. I think you simply want to separate your class PHP file away from your main file without making any obvious includes.

If so, you might want to use the __autoload() function:

<?php
function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>

This will notice that MyClass1 and MyClass2 haven't yet been defined and will call the autoload function with their class names as the parameter. So then MyClass1.php and MyClass2.php will be require_once'd.

Upvotes: 5

deceze
deceze

Reputation: 522332

You can autoload the Class file, you will still have to instantiate the Class by hand at some point. Or you will have to include a script that instantiates it for you. Or you re-architect your application so your actual script is included by another script, which pre-instantiates the Class for you.

In short: including the file can be automated, instantiating the Class not so much.

Upvotes: 3

Related Questions