Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中的重复类(方法/属性)调用_Php_Oop_Class - Fatal编程技术网

PHP中的重复类(方法/属性)调用

PHP中的重复类(方法/属性)调用,php,oop,class,Php,Oop,Class,下面是我编写的一些代码的摘录,这些代码基于同一类的方法分配$user->privilege。它似乎过于重复,我想知道我是否可以做些什么使它更具可读性——因为我在我看过的代码中没有看到过太多这种重复 $user -> privileges = $user -> get_privileges ( $user -> username ); 对我来说,这看起来并不特别重复,但基于类外的方法指定对象的属性有点不寻常。相反,这可能在对象构造函数内部得到更好的处理,这样就不需要在编码时记住

下面是我编写的一些代码的摘录,这些代码基于同一类的方法分配
$user->privilege
。它似乎过于重复,我想知道我是否可以做些什么使它更具可读性——因为我在我看过的代码中没有看到过太多这种重复

$user -> privileges = $user -> get_privileges ( $user -> username );

对我来说,这看起来并不特别重复,但基于类外的方法指定对象的属性有点不寻常。相反,这可能在对象构造函数内部得到更好的处理,这样就不需要在编码时记住设置属性:

class User {
    public $username;
    public $privileges;

    public function __construct() {
      // setup the user however that's done...

      // And assign privileges in the constructor
      $this->privileges = $this->get_privileges();
    }

    // In get_privilegs, rather than passing the username property,
    // just access it via $this->username.
    // Unless you need to use this method from time to time outside the class, it can be private
    private function get_privileges() {
      // Get privs for $this->username
    }
}

作为
$this->privileges=$this->get_privileges()的替代方案时,您可以在
get\u privileges()
方法中设置
$this->privileges
。然后您可以在构造函数中将其称为
$this->get_privileges()
,无需赋值。任何一种方法都有效。

当一种方法很昂贵时,我经常使用这种模式,我可以只为请求的其余部分存储结果:

class User {
    protected $_privileges = null;

    public function getPrivileges() {
        if ($this->_privileges == null) {
            // code to populate privileges array
            $this->_privileges = $privileges;
        }

        return $this->_privileges;
    }
}

这样一来,getPrivileges()只需做一次艰苦的工作,之后它会使用自己的本地缓存副本来处理该对象实例的其余请求。

为什么要存储已经可以访问的函数的结果?你在向矛盾敞开心扉!此外,考虑将<代码> $USER >用户名< /代码>作为 GeTyPraveStices()/Cube >的默认参数,这样您就可以省略它。是的,我更喜欢这个想法。作为OOP的新手,构造函数有时会把我扔到一个循环中。感谢您的帮助:)@DơngVăn您可以在对象构造函数中做很多有用的工作。第二种方法似乎效果更好,因为它从$uuu COOKIES中提取值,而$uu COOKIES在构造函数中似乎不起作用。@DơngVăn
$ucookie
在脚本中的任何地方都可以使用,包括构造函数。请确保拼写正确-您在评论中称之为
$\uu COOKIES
,但它只有一个下划线,没有S。您是对的,这里拼写错误,因为我将它们称为变量的集合实体。这是缺乏精确性:)