Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php oop - each class different file? import package? etc

Tags:

oop

php

I am used to working in languages such as C#/Java/Python where each class would have its own file, and for a class to see other classes, you would import the package containing those classes. How does this work in php? The documentation shows you how to create classes, but I don't understand how it all fits together in a php context. I know of the include statement, which just sticks the files together basically.

like image 896
BobTurbo Avatar asked Jan 21 '11 11:01

BobTurbo


4 Answers

You can use __autoload

function __autoload($class_name) {
    include 'classes/'.$class_name . '.php';
}

So place every single class in its own file in the classes folder. When you want to use that class it will include it. More info: http://php.net/manual/en/language.oop5.autoload.php

Update: When I answered this it was fully valid. Now it still works, but keep in mind PHP.net since then says this:

spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.

like image 95
Ákos Nikházy Avatar answered Oct 21 '22 01:10

Ákos Nikházy


The easiest way:

  • define your classes in "classes" directory
  • init application like shown below
  • name class filenames as their lowercase class name with .php suffix (MyClass => classes/myclass.php)

Init code:

set_include_path ( "./classes" );
spl_autoload_register ();

//class is automatically loaded from ./classes/myclass.php
$object_instance = new MyClass ();
like image 21
Kamil Tomšík Avatar answered Oct 20 '22 23:10

Kamil Tomšík


As of PHP 5.3.0 , it is recommended that you use the spl_autoload_register() function because __autoload() is said to be deprecated some time in the future.

An easy way to use this function:

1) Place each class file into the 'classes' folder

2) Run an anonymous function inside spl_autoload_register() which specifies your class folder:

spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.php';
});

Now when you try to use a class that is not defined in your code yet, it will check that class folder one last time before giving you an error.

like image 3
Douglas.Sesar Avatar answered Oct 21 '22 01:10

Douglas.Sesar


Imagine you have been making your object in PHP in a file called myObject.php

<?php

  class myObject
  {
    public function __construct()
    {
      echo "Hello, World";
    }
  }

?>

And in another file, you would like to use the object (let's call this myfile.php). You would have to include your object - like this:

<?php

  include("myObject.php");

  $intance = new myObject();

?>

Quite simple.

like image 1
Repox Avatar answered Oct 20 '22 23:10

Repox