2

I've got a little experience in PHP, but I mainly come from Python. The thing I so adore about Python is the way modules are handled. If I have a file called a.py in my directory, containing a class called MyClass I can simply import the class like this.

from a import MyClass

From PHP however, I know you can do:

include somefile.php

This imports and runs all code from the file, which makes it similar to the following in Python

from a import *

Doing a wildcard import however, leaves me clueless as to what I am actually importing and also causes namespace pollution. So my question; is there a way that I can import classes in PHP by naming them?

kramer65
  • 50,427
  • 120
  • 308
  • 488
  • 1
    this is what you want http://php.net/manual/en/language.namespaces.importing.php – ಠ_ಠ Aug 23 '13 at 18:06
  • Keep in mind that using namespaces in conjunction with autoloaders (http://stackoverflow.com/questions/1830917/how-do-i-use-php-namespaces-with-autoload) means you are limited to one class per file. I have no clue why you'd want two public classes in the same file though. – Sergiu Paraschiv Aug 23 '13 at 18:11

1 Answers1

0

The good practice in PHP is one class per file, not all classes in the same file for a module

ex:

classes/mynamespace/mypackage/IO.php
classes/mynamespace/mypackage/DB.php
classes/mynamespace/mypackage/log.php
...

Then you use an autoloader, every time you need a class in your code, the autoloader kicks in and loads it. If you are not using a framework which comes with its built-in autoloader, a good solution is to use the autoloader provided by composer, the depedncy manager for PHP: http://getcomposer.org/

Pascalc
  • 575
  • 1
  • 4
  • 5