Jump to content

Class member with same name as method?


phant0m

Recommended Posts

As the topic title suggests, how does PHP deal with object properties that has the same name as a method?

 

  class Test{
      protected $isTesting = true;

      public function isTesting(){
          var_dump($this->isTesting);
      }
  }

  $test = new Test;
  $test->isTesting();

 

But what if I wanted to run a function with the name that is stored in the property?

 

The code above behaves as intended, it outputs "true". Can this naming be used without concern? Or are there any pitfalls?

Link to comment
Share on other sites

But what if I wanted to run a function with the name that is stored in the property?

 

Like this?

$method = 'isTesting';
$test->$method();

 

or do you have something else in mind?

Yes, something like this:

$this->type = 'SomeClass';
$some_class = new $this->type('Constructor Param');

I know that this works^^ - but was if there was a method with the same name? public function type($param){}

 

 

@ignace, I guess you're right. But do you know where I can read up on this?

Link to comment
Share on other sites

I can't see why would it stop working...

 

Anyway, as ignace points out, it is introducing confusion.

 

 

One popular convention for boolean properties and their getter/setter method is as follows

 

class SomeClass {

  private $booleanVal;

  public function isBooleanVal($value = null) {
    if(!isset($value)) {
      return $this->booleanVal;
    } else {
      $this->booleanVal = (bool)$value;
    }

  }

}

$obj = new SomeClass();
$obj->isBooleanVal(true);
var_dump($obj->isBooleanVal());

 

This might be less confusing, although some people don't like getter/setter functionality stacked in one method.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.