简体   繁体   中英

PHP: Accessing properties pros/cons

As I see it, there are three approaches to accessing object properties in PHP:

1. Magic Methods

public function __get($property) { 
  if (property_exists($this, $property)) { 
    return $this->$property; 
  } 
} 

public function __set($property, $value) { 
  if (property_exists($this, $property)) { 
    $this->$property = $value; 
  } 
} 

2. Naive Getters and Setters

public function setName($name) {
  $this->name = $name; 
}

public function getName() {
  return $this->name; 
}

3. Directly

// Set name
$dog->name = "rover"; 
// Get name
$name = $dog->name;

My question is when should these approaches be used/avoided? (ie. What are the pros and cons of each?).

Purely in terms of speed, I've done some profiling and there's large performance differences between the three. On my machine, a million accesses took on average:

Magic Methods Speed
0.58 seconds

Naive Getters and Setters Speed
0.13 seconds

Direct Access Speed
0.05 seconds

Link: Complete results

That would seem to indicate the Magic Methods should be avoided unless necessary, and the same for naive getters and setters, but (of course) that's it's only a fraction of a second per million accesses on my machine, and "premature optimization is the root of all evil", as the saying goes.

So maybe speed shouldn't be the defining factor.

Obviously you may wish to do validation on the properties, so I can see how naive getters and setters would be useful with that, too.

So when should each of these approaches be used? What situations are they best suited to?

I realise this may be closed for being primarily opinion based, but I'm taking a chance that some good answers, with logic and data to back them up, might be generated :) Let's see!

In my practice I use (2): private variables + getters / setters.

Direct access (3) should be avoided according to SOLID ideology.

Magic Methods (1): I suggest it can be used (IMHO) but I can remember only 1 time I needed it during 15+ years of programming practice. And even if so, the validation is desired.

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