Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Options for Instatiating a Class in PHP

DZone's Guide to

Options for Instatiating a Class in PHP

· Web Dev Zone
Free Resource

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

If you want to instantiate a class in PHP, the class must be loaded into your application before you can use it. There are four ways you can load a class into your application: include, include_once, require or require_once. But when you use this, you must define all of the classes that you want to use in your application.

Another option is to use an autoload function, which will be called when your application attempts to instantiate a class that isn't loaded.

<?php
function __autoload($classname) {
    $filename = $classname . ".php";

    if(file_exists( $filename ))
    {
        include_once($filename);
    }
}

$class = new MyClass();
$class2 = new OtherClass();
?>

Below is another solution you can use, but you must have all your files inside a folder of your application. You can then search a folder for all PHP files and include all these files in your application. This uses the PHP function glob() which will search for a pattern of file names and return them as an array. You can use this array to loop through the values and include the file, like the following code:

foreach (glob('folder/*.php') as $filename)
{
    include_once $filename;
}

new Class();
new ClassTwo();
new ClassThree();


Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}