douwuying4709 2017-01-21 10:40
浏览 70
已采纳

为什么我的getter(__get)没有在PHP类中调用?

I have read all related question, but failed to remove the bug from my code. Please guide me about possible error in my code. When I try to call following code, it reports Error: Call to undefined method SessionManager::close() in E:\wamp64\www\mjs-cms\private\systemcore\helper\SessionManager.php on line 22 instead of "tried to call close".

Thanks in advance.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class SessionManager{
    public function __construct() {
        session_start();
    }
    public function is_exist($a){
        return isset($_SESSION["system".$a]);
    }

    public function add($a,$b){
        $_SESSION["system".$a]=$b;
    }
    public function  addCookies($a,$b){
        setcookie($a, $b, time() + (86400 * 30), "/"); // 86400 = 1 day
    }
    public function sessionKey(){
        return session_id();
    }
    public function value($k){
        if(!isset($_SESSION[$k]))
            $this->close("SESSION_NOT_DEFINED".__LINE__);
        return $_SESSION[$k];
    }
    public function __get($key)
    {
        echo "tried to call $key";
        return get_instance()->$key;
    }
}
  • 写回答

1条回答 默认 最新

  • doufei2194 2017-01-21 10:43
    关注

    __get method is for accessing undeclared properties of a class.

    For calling undeclared functions is __call or __callStatic.

    public function __call($method_name, $arguments)
    {
        echo "tried to call: $method_name";
    }
    

    If you want to use __get - you must call for undefined property. In this case it is not

    SessionManager::close()  // call method `close()`
    

    It must be:

    $sm = new SessionManager;
    $sm->propertyName;   // trying to access undefined property `propertyName` of an object
    

    Take into consideration that

    Property overloading only works in object context.

    which means that trying to access static property like

    SessionManager::staticProperty;
    

    will not work with __get.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog