dongxingqiu7943 2011-04-05 20:43
浏览 45
已采纳

PHP新手问题; “通知:未定义的属性”

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");
  • 写回答

3条回答 默认 最新

  • drtkyykai004574380 2011-04-05 22:26
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?