Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force PHP to throw an error on undefined property

Tags:

php

This will throw an error:

class foo
{
   var $bar;

   public function getBar()
   {
      return $this->Bar; // beware of capital 'B': "Fatal:    unknown property".
   }

}

But this won't:

class foo
{
   var $bar;

   public function setBar($val)
   {
      $this->Bar = $val; // beware of capital 'B': silently defines a new prop "Bar"
   }

}

How can I force PHP to throw errors in BOTH cases? I consider the second case more critical than the first (as it took me 2 hours to search for a d....ned typo in a property).

like image 730
Axel Amthor Avatar asked Jun 21 '13 13:06

Axel Amthor


1 Answers

You can use magic methods

__set() is run when writing data to inaccessible properties.

__get() is utilized for reading data from inaccessible properties.

class foo
{
   var $bar;

   public function setBar($val)
   {
      $this->Bar = $val; // beware of capital 'B': silently defines a new prop "Bar"
   }

   public function __set($var, $val)
   {
     trigger_error("Property $var doesn't exists and cannot be set.", E_USER_ERROR);
   }

   public function  __get($var)
   {
     trigger_error("Property $var doesn't exists and cannot be get.", E_USER_ERROR);
   }

}

$obj = new foo(); 
$obj->setBar('a');

It will cast error

Fatal error: Property Bar doesn't exists and cannot be set. on line 13

You can set Error Levels according to PHP error levels

like image 181
Robert Avatar answered Sep 30 '22 16:09

Robert