简体   繁体   中英

PHP override get set methods

Is it possible to override the get and set methods for parameters that I already have set? So every time I set a param I have access to work with it/ validate it?

class User {

   public $username;

   function custom_set($name, $value) {
      if(strlen($value) < 5) {
        return "not long enough";
      } else {
        $this->$name = $value;
      }

   }  
}

$u = new User();
$u->username = "ted";
echo $u->username;

Outputs: "not long enough"

This is a very simplified example that I just wrote out and probably contains errors, it's just to convey what I am trying to do.

Basically everytime I call $u->username = "anything"; I want the custom_set method to be called.

I don't want to do the validation in the constructor and I don't want to create separate methods like $u->setVal("ted");

Is this possible?

Implement the __set method. This is called when attempted to access inaccessible properties.

function __set($name, $value) {
    $this->custom_set($name, $value);
}

Note, however, that $username is a public property so this will not work unless it is declared private or protected .

Make those attributes protected or private then __get and __set will be called and you can delegate to whatever logic you want.

Personally, I have yet to see a case where i would consider using a public property for anything.

您是在说魔术方法吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM