How to use a PHP class from another file?

Php

Php Problem Overview


Let's say I've got two files class.php and page.php

class.php

<?php 
	class IUarts {
		function __construct() {
			$this->data = get_data('mydata');
		}
	}
?>

That's a very rudamentary example, but let's say I want to use:

$vars = new IUarts(); 
print($vars->data);

in my page.php file; how do I go about doing that? If I do include(LIB.'/class.php'); it yells at me and gives me Fatal error: Cannot redeclare class IUarts in /dir/class.php on line 4

Php Solutions


Solution 1 - Php

You can use include/include_once or require/require_once

require_once('class.php');

Alternatively, use autoloading by adding to page.php

<?php 
function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

$vars = new IUarts(); 
print($vars->data);    
?>

It also works adding that __autoload function in a lib that you include on every file like utils.php.

There is also this post that has a nice and different approach.

https://stackoverflow.com/questions/791899/efficient-php-auto-loading-and-naming-strategies

Solution 2 - Php

In this case, it appears that you've already included the file somewhere. But for class files, you should really "include" them using require_once to avoid that sort of thing; it won't include the file if it already has been. (And you should usually use require[_once], not include[_once], the difference being that require will cause a fatal error if the file doesn't exist, instead of just issuing a warning.)

Solution 3 - Php

Use include_once instead.
This error means that you have already included this file.

include_once(LIB.'/class.php');

Solution 4 - Php

Use include("class.classname.php");

And class should use <?php //code ?> not <? //code ?>

Solution 5 - Php

use

require_once(__DIR__.'/_path/_of/_filename.php');

This will also help in importing files in from different folders. Try extends method to inherit the classes in that file and reuse the functions

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXhynkView Question on Stackoverflow
Solution 1 - PhplmcanavalsView Answer on Stackoverflow
Solution 2 - PhpRy-View Answer on Stackoverflow
Solution 3 - PhpRicardo Alvaro LohmannView Answer on Stackoverflow
Solution 4 - PhpManobendronath BiswasView Answer on Stackoverflow
Solution 5 - PhpAdnan FayazView Answer on Stackoverflow