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);

Link to comment
Share on other sites

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);

Link to comment
Share on other sites

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

Link to comment
Share on other sites

  • 4 weeks later...
  • 2 weeks later...
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.