Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a PHP class from another file?

Tags:

php

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

like image 309
Xhynk Avatar asked Jan 16 '13 03:01

Xhynk


People also ask

How do you call a class in PHP?

When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable. As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).

How do I jump to another file in PHP?

Answer: Use the PHP header() Function You can simply use the PHP header() function to redirect a user to a different page. The PHP code in the following example will redirect the user from the page in which it is placed to the URL http://www.example.com/another-page.php .


2 Answers

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

like image 54
lmcanavals Avatar answered Sep 23 '22 01:09

lmcanavals


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

like image 28
Ry- Avatar answered Sep 22 '22 01:09

Ry-