从 PHP 中的成员函数访问私有变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1762135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
accessing private variable from member function in PHP
提问by Carson Myers
I have derived a class from Exception, basically like so:
我从 派生了一个类Exception,基本上是这样的:
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 MyExceptionlike so:
然后,我从MyException这样得出:
class SpecialException extends MyException {
private $_type = "superspecial";
}
If I throw new SpecialException("bla")from a function, catch it, and go echo $e, then the __toStringfunction should load a template, display that, and then not actually return anything to echo.
如果我throw new SpecialException("bla")从一个函数中捕获它,然后 go echo $e,那么该__toString函数应该加载一个模板,显示它,然后实际上不返回任何内容来回显。
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.phpon line 74
致命错误:第74行无法访问C:\path\to\exceptions.php 中的私有属性 SpecialException::$_type
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 $_typevariable is (as shown) that I want a different div class to be used depending on the type of exception caught.
谁能解释为什么我在这里违反规则?我是不是在用这段代码做一些非常诙谐的事情?有没有更惯用的方法来处理这种情况?$_type变量的要点是(如图所示)我希望根据捕获的异常类型使用不同的 div 类。
回答by Fivell
just an example how to access private property
只是一个如何访问私有财产的例子
<?php
class foo {
private $bar = 'secret';
}
$obj = new foo;
if (version_compare(PHP_VERSION, '5.3.0') >= 0)
{
$myClassReflection = new ReflectionClass(get_class($obj));
$secret = $myClassReflection->getProperty('bar');
$secret->setAccessible(true);
echo $secret->getValue($obj);
}
else
{
$propname="* 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
fooclass Foo {
private $bar = "Foo::Bar";
}
bar";
$a = (array) $obj;
echo $a[$propname];
}
回答by dfilkovi
Name the variable protected:
将变量命名为 protected:
$foo = new Foo;
$getFooBarCallback = function() {
return $this->bar;
};
$getFooBar = $getFooBarCallback->bindTo($foo, 'Foo');
echo $getFooBar(); // Prints Foo::Bar
回答by Christos Lytras
See my answer here: https://stackoverflow.com/a/40441769/1889685
在此处查看我的答案:https: //stackoverflow.com/a/40441769/1889685
As of PHP 5.4, you can use the predefined Closureclass to bind a method/property of a class to a delta functions that has access even to private members.
从PHP 5.4 开始,您可以使用预定义的Closure类将类的方法/属性绑定到甚至可以访问私有成员的增量函数。
For example we have a class with a private variable and we want to access it outside the class:
例如,我们有一个带有私有变量的类,我们想在类外访问它:
$foo = new Foo;
$getFooBar = function() {
return $this->bar;
};
echo $getFooBar->call($foo); // Prints Foo::Bar
PHP 5.4+
PHP 5.4+
<div class="<?php echo get_class($this); ?>class">
As of PHP 7, you can use the new Closure::callmethod, to bind any method/property of an obect to a callback function, even for private members:
从 PHP 7 开始,您可以使用新Closure::call方法将对象的任何方法/属性绑定到回调函数,即使是私有成员:
PHP 7+
PHP 7+
##代码##回答by California Kidd
Cannot access $this outside of a class. Instead, need to call an instance of the class. Then, access a function within the class which will return the message.
无法在类之外访问 $this。相反,需要调用类的实例。然后,访问将返回消息的类中的函数。
回答by RMcLeod
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.
您需要将访问权限设置为受保护。私有意味着它只能从它自己的类内部访问,不能被继承。Protected 允许它被继承,但它仍然不能从类外部直接访问。
回答by Greg
If you check the visibilitydocumentation, buried in a comment is:
如果您检查可见性文档,埋在评论中的是:
// We can redeclare the public and protected method, but not private
// 我们可以重新声明 public 和 protected 方法,但不能重新声明私有
You should make it protectedto do what you're trying to do.
你应该让它protected去做你想做的事。
Incidentally, it looks like you're just setting it to be the class name - you could just use get_class():
顺便说一句,看起来您只是将其设置为类名-您可以使用get_class():
回答by Ben Fransen
You should indeed change the accessmodifier to protectedwhen you'e builing inheritance classes.
您确实应该在构建protected继承类时将访问修饰符更改为。
One extra point though; don't use return "";but just use return;
不过要多加一分;不要使用,return "";而只是使用return;

