I have derived a class from Exception
, basically like so:
class MyException extends Exception {
private $_type;
public function type() {
return $this->_type; //line 74
}
public function __toString() {
include "sometemplate.php";
return "";
}
}
Then, I derived from MyException
like so:
class SpecialException extends MyException {
private $_type = "superspecial";
}
If I throw new SpecialException("bla")
from a function, catch it, and go echo $e
, then the __toString
function should load a template, display that, and then not actually return anything to echo.
This is basically what's in the template file
<div class="<?php echo $this->type(); ?>class">
<p> <?php echo $this->message; ?> </p>
</div>
in my mind, this should definitely work. However, I get the following error when an exception is thrown and I try to display it:
Fatal error: Cannot access private property SpecialException::$_type in C:\path\to\exceptions.php on line 74
Can anyone explain why I am breaking the rules here? Am I doing something horribly witty with this code? Is there a much more idiomatic way to handle this situation? The point of the $_type
variable is (as shown) that I want a different div class to be used depending on the type of exception caught.
Name the variable protected:
just an example how to access private property
You need to set the access to protected. Private means that it can only be accessed from within it's own class and can't be inherited. Protected allows it to be inhherited but it still can't be accessed directly from outside the class.
If you check the visibility documentation, buried in a comment is:
You should make it
protected
to do what you're trying to do.Incidentally, it looks like you're just setting it to be the class name - you could just use
get_class()
:You should indeed change the accessmodifier to
protected
when you'e builing inheritance classes.One extra point though; don't use
return "";
but just usereturn;
See my answer here: https://stackoverflow.com/a/40441769/1889685
As of PHP 5.4, you can use the predefined
Closure
class to bind a method/property of a class to a delta functions that has access even to private members.The Closure class
For example we have a class with a private variable and we want to access it outside the class:
PHP 5.4+
As of PHP 7, you can use the new
Closure::call
method, to bind any method/property of an obect to a callback function, even for private members:PHP 7+