从PHP中的成员函数访问私有变量

从PHP中的成员函数访问私有变量

本文介绍了从PHP中的成员函数访问私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Exception派生了一个类,基本上是这样的:

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

    }

}

然后,我像这样从MyException派生:

Then, I derived from MyException like so:

class SpecialException extends MyException {

    private $_type = "superspecial";

}

如果我从某个函数中throw new SpecialException("bla")捕获它并转到echo $e,则__toString函数应加载一个模板,显示该模板,然后不实际返回任何内容以回显.

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:

有人可以解释为什么我在这里违反规则吗?我在用这段代码做些非常机灵的事情吗?有没有更惯用的方式来处理这种情况? $_type变量的要点是(如图所示),我希望根据捕获的异常类型使用不同的div类.

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.

推荐答案

命名受保护的变量:

* 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

这篇关于从PHP中的成员函数访问私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:46