douyong4842 2013-09-20 01:37
浏览 28

类中的变量(其值来自另一个类)不可用于方法[关闭]

I'm new to OOP so there's probably something fundamental I'm missing here. In the Foo class, the $this->user_group variable is not available to the bar() method. Why is that? And is there a less messy way to get these classes to all talk to each other than including the $DB (and others) every instantiation (this gets hairier with my actual code, which has many more classes). Here's an example:

class Foo {
    private $Auth, $user_group;

    function __construct($DB) {
        $this->Auth       = new Auth($DB);
        $this->user_group = $this->Auth->get_user_permissions_group();
        // ("echo $this->user_group;" here will output the correct value)
    }

    public function bar() {
        // ("echo $this->user_group;" here will output nothing)
        return ($this->user_group > 1 ? 'cool!' : 'not cool!');
    }
} 

class Auth {
    private $DB;

    function __construct($DB) {
        $this->DB = $DB;
    }

    public function get_user_permissions_group() {
        $result = $this->DB->query('return user permissions level from DB');
        return $result; // int, 1-3
    }
}


$DB = new Database();
$Foo = new Foo($DB);
echo $Foo->bar();
  • 写回答

1条回答 默认 最新

  • dousi4472 2013-09-20 01:49
    关注

    user_group should be visible in the bar function. Are you sure you didn't mess up your curly brace blocks somewhere in the code and that Auth->get_user_permissions_group() returns an integer?

    You can double check the following code on this site. It's working fine for me.

    class Foo {
        private $user_group;
    
        function __construct($group) {
            $this->user_group = $group;
        }
    
        public function bar() {
            return ($this->user_group > 1 ? 'cool!' : 'not cool!');
        }
    } 
    
    
    $Foo = new Foo(3);
    echo $Foo->bar();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据