61

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

5 Answers 5

79

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.

Efficient PHP auto-loading and naming strategies

Sign up to request clarification or add additional context in comments.

2 Comments

"__autoload() is deprecated, use spl_autoload_register() instead" Since this result is fairly high on google, maybe someone should edit it and point this out more clearly?
This accepted answer is not straight to the point about the question and the error message shown (as a result of multiple inclusion of the same class). Not downvoting as it is nevertheless useful and correct.
12

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.)

Comments

9

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

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

Comments

3

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

Comments

2

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

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

2 Comments

That second thing you said isn't specific to this question or correct. <? ?> is just newer syntax, I believe it can be enabled or disable in the php.ini. (Sorry to resurrect this)
I think what he was saying is that shorthand version isnt always enabled on all servers and occasionally you may be using a webhosting environment where you can't modify the php.ini, so it is safer and more compatible if you use <?php instead of the shorthand <? version.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.