开发者

PHP OOP - Is it a good/bad directly adressing properties?

I w开发者_开发百科ill try to show this by an example:

class DogShelter
{
  private $dog;

  public function handleDogDirect( )
  {
     $this->dog = trim( $this->dog );
     $this->dog = rtrim( $this->dog, 'abc' );
     $this->dog = strtolower( $this->dog );
     $this->dog = basename( $this->dog );
  }

  public function handleDogIndirect( )
  {
     $dog = $this->dog;

     $dog = trim( $dog );
     $dog = rtrim( $dog, 'abc' );
     $dog = strtolower( $dog );
     $dog = basename( $dog );

     $this->dog = $dog;
  }
}

Which is the better function in different cases - handleDogDirect or handleDogIndirect?

  • Why?
  • Which one is probably faster?
  • Which one should I use?

By the way: Since the rep recalc, I can't login with my OpenID from wordpress anymore. It keeps saying No OpenID endpoint found.. I would really appreciate any help.


I would use handleDogDirect since it's accessing the instance of the $dog which seems to be what you wanted to achieve. The latter function seems to create an unnecessary variable to perform the same function.

As a convention whenever I am using properties of the class I am within inside class functions I always use $this keyword directly.

If there is a performance issue with either of the two, its probably negligible. I strongly suggest to worry about performance issues when it's time to worry about performance.


I don't think there's a point in creating a new variable for no reason. I think the performance hit if any is negligible. What should actually happen is that before the value is placed in the class variable it should be clean up ie within setDog().


I would say this is more an issue of personal coding style.

I sometimes do it like handleDogIndirect( ) because it makes more sense to me the way I visualize my code, becuase it involves less typing (especially less holding down of the shift key), and because I think it reads better.

I'll try to explain why it makes more sense to me. The functions are their own little world, that's why they have their own scope. They're happy when they work in that scope, so I first want to make sure that I pull everything they will need into their scope. Once that's done I don't have to think about what's going on anywhere else, only what's local to that function. Less mind clutter.

Then when they're done doing their work I put their useful data back where it belongs.

I think it especially helps if you have a method that's somewhat long or complicated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜