Jump to content

Need help: how to catch acess of undefined class properties


baman

Recommended Posts

Hello. I am learning OO with PHP and have hit a problem.

Some code runs as perfectly valid code, where i would like PHP to issue a warning / error.

I guess this is because of the loose typing of PHP, however this cause real bugs go unnoticed in my code and i am looking for a way to be able to detect this.

 

The code sample does not produce any warning/error using "error_reporting=E_ALL" with php 5.2.10

 

Do anyone have a idea or suggestion?

 

class Objekt
{
var $foo;
var $bar;
}

$x = new Objekt();
$x->foo = 4;
var_dump($x);

$x->baz = 9; //i would like this to cause an warning because "baz" is a undefined property of the Objekt class. but it dont and "baz" is added to the object
var_dump($x);

In PHP5 you could probably do something with magic getters and setters

class Objekt {
public $foo;
public $bar;

public function __set($name, $value) {
	if (!isset($this->$$name)) {
		throw new Exception($name.' property does not exist');
	}
}
}

$x = new Objekt();
$x->foo = 4;
var_dump($x);

$x->baz = 9;
var_dump($x);

Mark: Thank you a ton!

 

By overriding the internal setter with __set() like you suggest, i now can control this stuff as I wanted!

 

Niel: It was avoiding adding extra checks (like property_exists() ) that was my goal, but thanks for your reply

  • 4 weeks later...
  • 2 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.