简体   繁体   中英

How can i include files to use class in other included files?

I have 3 files in root folder

main.php:

require_once 'function.php';
load_layout($template="header"); // load header.php -- there are echo $session->user_id; code in header.php that not work
echo $session->user_id; //work

function.php:

require_once 'ses.php';
function load_layout($template="") {
    include ('header.php');
}

ses.php :

class Session {
    public $user_id = "1";
    public function userinfoss() {
        return $this->user_id;
    }
}

$session = new Session();

and header.php

require_once 'function.php';
echo $session->user_id; //not work in main.php loading but work if header.php run seprate

echo $session->user_id; work if header.php run seprately but it is included in main.php and echo $session->user_id; not work in main.php loading

How can I change my codes to display echo $session->user_id; in included files?

update:

I create a function in ses.php:

    class Session {
        public $user_id = "1";
        public function userinfoss() {
            return $this->user_id;
        }
    }

    $session = new Session();

    function testfun() {
    global $session;
    echo $session->user_id;
}

So call this function in header.php and worked but Why $session->user_id not work ?

When you call main.php , the first require_once 'function.php'; will work, and it will call require_once 'ses.php'; , which will make the $session variable available in function.php and in main.php ;

When header.php gets included, however, the require_once 'function.php'; it contains will not do anything (because function.php has already been included), and the $session variable will not be available in header.php .


Ideally, you should reorganize your code so that you don't have 2 files ( main.php and header.php ) that depend on the same file ( function.php ).

So, maybe you can replace:

require_once 'function.php'
load_layout($template="header");

in main.php by:

require_once 'header.php';

If you can't reorganize your code, then you can use a global variable for $session . Add:

global $session;

before

$session = new Session();

in ses.php .

You also need to add

global $session;

before

echo $session->user_id;

in header.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM