Dương Văn
Dương Văn

Reputation: 481

Repetitive class (method/property) invoking in PHP

The following is an excerpt from some code I wrote to assign the $user->privilege based on a method from that same class. It seems excessively repetitive, and I am wondering if there is something I can do to make it more readable -- given that I haven't seen this kind of repetition too much in codes I have looked at.

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

Upvotes: 1

Views: 57

Answers (2)

Jason McClellan
Jason McClellan

Reputation: 3021

I use this pattern a lot when a method is expensive and I can just store the result for the remainder of the request:

class User {
    protected $_privileges = null;

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

        return $this->_privileges;
    }
}

That way getPrivileges() will only do the hard work once and afterward it uses its own locally cached copy for the remainder of the request for that object instance.

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270727

It doesn't look particularly repetitious to me, but it is a little unusual to be assigning an object's property based on a method outside the class. Instead, this might be better handled inside the object constructor, eliminating the need for you to remember to set the property when coding:

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
    }
}

And as an alternative to $this->privileges = $this->get_privileges(); called in the constructor, you might just set $this->privileges inside the get_privileges() method. Then you can just call it as $this->get_privileges() in the constructor, no assignment necessary. Either way works.

Upvotes: 2

Related Questions