2

I'm trying to include a custom path to a certain file using php's set_include_path. Here's the code:

file.php

<?php
    $path = 'classes/';
    set_include_path(get_include_path() . PATH_SEPARATOR . $path);
    $obj = new MyClass();
    $obj->methodCall();
?>

Here's my root directory structure

www
|_webapp
       |_classes
               |_MyClass.php
       |_nbproject
       |_file.php

All I get when I execute the script is this error message: Fatal error: Class 'MyClass' not found in C:\wamp\www\webapp\file.php. I have tried including the file using require and it works but I have hit a wall with set_include_path. Does anybody know what I can do about this?

Thanks

Tafadzwa Gonera
  • 352
  • 6
  • 20
  • Just saying "when trying to include files, look in folders A, B and C" doesn't magically say "to load class Foo, include file Foo.php". You need to either explicitly `include`/`require` the file with the class definition, or utilize an autoloader. – DCoder Dec 31 '12 at 12:32
  • I have utilized both `include/require` and `spl_autoload_register` for the same purpose but I never encountered any error. Why then is `set_include_path` not working for the same purpose? – Tafadzwa Gonera Dec 31 '12 at 12:38
  • Possibly because you specified a relative path to the classes directory instead of absolute? Hard to say. – DCoder Dec 31 '12 at 12:41
  • I think I misunderstood the behavior of `set_include_path`. I was under the impression that it behaves like `__autoload`. So I explicitly included the file and it works. This is so embarrassing...how did I miss that?! – Tafadzwa Gonera Dec 31 '12 at 12:48

2 Answers2

2
  1. You're adding a relative path to the global include path. Is that what you intended?
  2. You are possibly not including the file where class MyClass is defined. set_include_path() allows to omit the path in the require_once statement, not to omit the statement itself.

I have the impression that the tool you have in mind is class autoloader.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • You are right I was under the impression that `set_include_path()` behaves like `__autoloader`. I included the file and it works. God, how on earth did I miss that?!...It's embarrassing! – Tafadzwa Gonera Dec 31 '12 at 12:50
0

You choose include method like this format include 'path/filename.php'

prasobh
  • 95
  • 3
  • `include` works like I pointed earlier but `set_include_path` doesn't...I must be missing something but I don't know what it is – Tafadzwa Gonera Dec 31 '12 at 12:43