imns
imns

Reputation: 5082

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?

Upvotes: 0

Views: 4114

Answers (3)

prodigitalson
prodigitalson

Reputation: 60413

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.

Upvotes: 2

Hamish
Hamish

Reputation: 23316

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.

Upvotes: 3

Aaron Hathaway
Aaron Hathaway

Reputation: 4315

Are you talking about Magic Methods?

Upvotes: 0

Related Questions