Carson Myers Carson Myers - 1 year ago 81
PHP Question

accessing private variable from member function in PHP

I have derived a class from

, 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
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
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>


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
variable is (as shown) that I want a different div class to be used depending on the type of exception caught.

Answer Source

Name the variable protected:

* Public: anyone either inside the class or outside can access them
* Private: only the specified class can access them. Even subclasses will be denied access.
* Protected: only the specified class and subclasses can access them
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download