开发者

Fatal error: Call to undefined method stdClass::My()

开发者 https://www.devze.com 2023-03-28 20:12 出处:网络
I am getting this error when I call for the function My() for t开发者_StackOverflowhe second time. The first time (when I\'m calling for the user_id) everything seems to be fine.. Stripped down code:

I am getting this error when I call for the function My() for t开发者_StackOverflowhe second time. The first time (when I'm calling for the user_id) everything seems to be fine.. Stripped down code:

class User {
    function My($field) {
        global $user;
        global $db;
        global $sessions;

        if ($sessions == 2) {
            $user = $db->Row("SELECT * FROM users WHERE username='".$_SESSION['username']."'"); 
            return $user->$field;
        }
    }
}

$user = new User;

class Index {
    function Startup() {
        global $user;

        $user_id = $user->My("user_id");
        $name = $user->My("firstname")." ".$user->My("surname");
    }
}

Any suggestions would be greatly appreciated.


Sorry my first answer was incorrect!

Because you define $user global in both My() and Startup() you are reffering to the same data in both contexts.

The frist time everything is fine because $user has been initialized to a user object somewhere in your code. But the $db->Row() method inside your My() function changes the global $user to an stdClass which has no My() opreation.

Solution: remove the word global before $user in My()


You have to initalize the variable first like

$user = new User();
$user->my();

Also please never use global unless you know what you are doing.

0

精彩评论

暂无评论...
验证码 换一张
取 消