How to use a PHP class from another file?

前端 未结 5 1651
庸人自扰
庸人自扰 2020-12-05 06:41

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

class.php



        
相关标签:
5条回答
  • 2020-12-05 06:48

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

    0 讨论(0)
  • 2020-12-05 06:49

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

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

    0 讨论(0)
  • 2020-12-05 06:56

    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

    0 讨论(0)
  • 2020-12-05 06:57

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

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

    0 讨论(0)
  • 2020-12-05 07:03

    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

    0 讨论(0)
提交回复
热议问题