2

For some weird reason, I just cannot catch that exception when it happens

here is the code, it should work but I keep getting

Fatal error: Uncaught Error: Cannot use object of type Stuff as array in...

code:

try{
    class Stuff
    {

    }

    $stuff= new Stuff();
    $stuff["test"]=0;   <<<<<<< this should trigger the below catch 
}
catch (Exception $e) {
    $myLogger->Log($e);
}

thanks

phil123456
  • 211
  • 3
  • 13
  • 1
    You need to catch `Error` (if you only want errors) or `Throwable` (if you want to catch everything) to catch errors. See also [LugiHaue's answer to this question](https://stackoverflow.com/a/48381661/2007837). – hsan Jan 17 '19 at 08:36
  • ok thanks, but if you dont put that as an answer then I cannot validate it :-) I'll check these out – phil123456 Jan 17 '19 at 09:29

3 Answers3

1

here is the working answer :

try{
    class Stuff
    {
        $test = null; 
    }

    $stuff= new Stuff();
    $stuff->test = 0;
}
catch (Throwable $e) {
    $myLogger->Log($e);
}
phil123456
  • 211
  • 3
  • 13
0

Try this. use another catch to get fatal errors

try{
    class Stuff
    {

    }

    $stuff= new Stuff();
    $stuff["test"]=0;   <<<<<<< this should trigger the below catch 
} catch (Exception $e) {
    $myLogger->Log($e);
}  catch (Error $e) {
    // Handle error
    echo $e->getMessage(); // Call to a member function method() on string
} catch (Throwable $e) {
        // Handle error
        echo $e->getMessage(); // Call to undefined function undefinedFunctionCall()
    }
-1

Try this. It always helpfull

try{
    class Stuff
    {
        $test = null; 

        public function getTest()
        {
            return $this->test; 
        }

        public function setTest($value)
        {
            $this->test = $value; 
        }
    }

    $stuff= new Stuff();
    $stuff->setTest(0);
    echo $stuff->getTest();
}
catch (Exception $e) {
    $myLogger->Log($e);
}

Otherwise if you want to convert an object into array then try this.

$stuff= new Stuff();
$stuff = (array)$stuff;

This will convert an object to array (By type casting)

Otherwise set directly by doing this

try{
    class Stuff
    {
        $test = null; 
    }

    $stuff= new Stuff();
    $stuff->test = 0;
}
catch (Exception $e) {
    $myLogger->Log($e);
}
  • 1
    this does not answer the question... I WANT to log the exception, not to correct it... try my code, you'll see the exception is not catched as it should....sounds like a bug in php itself – phil123456 Jan 17 '19 at 08:15
  • Its a Fatal Erro and Exceptioin $e cannot get the fatal error you have to add another catch to get fatal error – Abdulrehman Sheikh Jan 17 '19 at 10:09