Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force PHP to error on non-declared variables? In objects?

Is there any way to force PHP to blow up (error, whatever) if I misspell a variable name? What about if I'm using an instance of a class and I spell the name of a variable wrong?

[I know that I should just get used to it, but maybe there's a way to enforce name checking?]

Thanks!

Edit: Sorry, that wasn't very specific. Here's the code, and I would like to get two errors. Right now I only get one (for the last line).

error_reporting(E_ALL|E_STRICT);
class Joe {
    public $lastName;
}

$joe = new Joe();
$joe->lastNombre = "Smith";
echo "And here it is " . $jose;
like image 945
Dan Rosenstark Avatar asked Dec 28 '08 19:12

Dan Rosenstark


4 Answers

Here is something I whipped up really quickly to show how you can trigger errors when something like that happens:

<?php

error_reporting( E_ALL | E_STRICT );

class Joe {
    public $lastName;

    public function __set( $name, $value ) {
        if ( !property_exists( $this, $name ) ) {
            trigger_error( 'Undefined property via __set(): ' . $name, E_USER_NOTICE );
            return null;
        }
        $this->$name = $value;
    }

    public function __get( $name ) {
        if ( !property_exists( $this, $name ) ) {
            trigger_error( 'Undefined property via __get(): ' . $name, E_USER_NOTICE );
            return null;
        }
        return $this->$name;
    }
}

$joe = new Joe();
$joe->lastNom = "Smith";
echo $joe->lastNom , "\n";

?>
like image 96
Nick Presta Avatar answered Oct 17 '22 15:10

Nick Presta


From the PHP docs on error_reporting:

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
like image 38
Paolo Bergantino Avatar answered Oct 17 '22 15:10

Paolo Bergantino


You could try:

error_reporting(E_ALL|E_STRICT);

EDIT: OK, I've now read the updated question. I think you're out of luck. That's valid in PHP. Some say it's a feature. :)

like image 2
PEZ Avatar answered Oct 17 '22 17:10

PEZ


You can use this in your code:

error_reporting(E_ALL);

or this in php.ini

php_error_reporting=5

http://us2.php.net/error_reporting

like image 1
Ryan Doherty Avatar answered Oct 17 '22 17:10

Ryan Doherty