PHP Newbie question; "notice: undefined property"

Mansiemans picture Mansiemans · Apr 5, 2011 · Viewed 13.4k times · Source

I'm running the following code:

class Foo {  
    private $var = 0;

    function isVarSet () {
           return ($this->var != 0);
    }
}

...

foo = new Foo();

results in an "undefined property" notice: foo::$var on my PHP (ver. 5.3.5).

if I rewrite just the function isVarSet():

function isVarSet() {
    if (isset($this->var))
        return ($this->var != 0);
    return false;
}

the notice disappears.

This I do not understand. $var is set in both cases, why would it be an undefined property? Why do I need to use isset() to prevent this notice? Also, why does the notice refer to $var with the scope operator :: ? I'm not using a static class, I'm using an instance foo. $foo->isVarSet() should access a $var that is both defined and non-static.

I've been working on this for hours now and read all other answers on the undefined property notice, but this one I just don't get. Please enlighten me, StackOverFlow masters.


the code in my application:

<?php

class session {

    private $userId = 0;

    function __construct() {
    session_start();
    $this->setUserId();
    }

    public function isLoggedIn() {
    //if (isset($this->userId))
        return ($this->userId != 0);
    //return false;
    }

    function getUserId() {
    if (isset($this->userId))
        return $this->userId;
    else
        return false;
    }

    private function setUserId() {
    if (isset($_SESSION['userId'])) {
        $this->userId = $_SESSION['userId'];        
    } else 
        unset($this->userId);       
    }

    public function login($user) {
    if ($user != null) {        
        $_SESSION['userId'] = $user->id;
        $this->userId = $user->id;
    }
    }

     public function logout() {
    unset($_SESSION['userId']);
    unset($this->userId);   
    }    
}

$session = new Session();

?>

The call to the session class is made like so:

if ($session->isLoggedIn())
redirectToLocation("../public/index.php");

Answer

Wrikken picture Wrikken · Apr 6, 2011

(after the whole edit).

What do you think this line does (in setUserId):

 unset($this->userId);

You might just want to set it to 0 as previous (which you recognize as not logged in:

 $this->userId = 0;

Or:

 $this->userId = null;

Take your pick.