SuprF1y
SuprF1y

Reputation: 100

Require declaration of properties before assignment

The following is legal in php.

class Foo{
    function setBar($bar){
        $this->bar = $bar;
    }
}

Is there a way to generate a notice that property Foo#bar hasn't been declared before use? I'm sick of wasting time debugging typos.

Upvotes: 0

Views: 185

Answers (1)

JvdBerg
JvdBerg

Reputation: 21856

I think this is what you are after:

class Foo
{    
  function setBar( $bar )
  {
    $this->bar = $bar;
  }

  public function __set( $name, $value )
  {
    throw new Exception( 'Can not set property ' . $name );
  }    
}

$foo = new Foo();
$foo->setBar( 'bar' );

What happens here is that when a class property is called that is out of scope, the magic __get or __set is called. There you can decide how to handle that situation.

Upvotes: 2

Related Questions