可以通过反射类访问的公共、私有、受保护类有什么用?


what is the use of public, private, protected class where it can be access via reflection class?

这是为了安全目的和封装我们有Public,Private, Protected类但有一个问题仍然在脑海中出现如果我们仍然可以访问或知道这些类的所有成员无论是Public, Private还是Protected,这意味着什么??

例如:

<?php
 class GrandPas   // The Grandfather's class
  {
   public     $name1 = 'Mark Henry';  // This grandpa is mapped to a public modifier
   protected  $name2 = 'John Clash';  // This grandpa is mapped to a protected  modifier
   private    $name3 = 'Will Jones';  // This grandpa is mapped to a private modifier
  }
#Scenario: Using reflection
$granpa = new ReflectionClass('GrandPas'); // Pass the Grandpas class as the input for the Reflection class
$granpaNames=$granpa->getDefaultProperties(); // Gets all the properties of the Grandpas class (Even though it is a protected or private)

 echo "Printing members the 'reflect' way..<br>";
 foreach($granpaNames as $k=>$v)
  {
    echo "The name of grandpa is $v and he resides in the variable $k<br>";
  }

的输出将是:

#Scenario Using reflection
Printing members the 'reflect' way..
The name of grandpa is Mark Henry and he resides in the variable name1
The name of grandpa is John Clash and he resides in the variable name2
The name of grandpa is Will Jones and he resides in the variable name3

我们可以看到班级的所有成员是否其Private, Protected or Public。那么OOP的概念是什么呢?

PS:取自Shankar Damodaran的例子

TL;

如果你可以做某事,并不意味着你应该去做

这是旨在提供有关实体的元信息的东西,但它的实际用例是有争议的,几乎总是可以用其他东西代替。关键不是说它不好,而是说——如果你想在你的架构中使用它,那么很可能,你的架构中有一个缺陷。

一种"去"的方式…

实际上,你可以在PHP中不使用Reflection访问受保护的/私有属性。例如,Closure::bindTo()如下:

class Test
{
   private $x = 'foo';
}
$z = new Test();
$y = function()
{
   return $this->x;
};
$y = $y->bindTo($z, $z);
echo $y(); //foo

和. .那又怎样?每种语言特性都有好的用途,也有不好的用途。我们称之为"好实践"answers"坏实践"(嗯,老实说,我很难记住PHP中global之类的"好实践",但这不在这个问题之列)。更重要的是,PHP中有很多东西你可能会用错方法——这使得它成为一门很难的语言——从某种意义上说,学习这门语言并不难,但很难正确地使用它的所有功能,因为这需要坚实的体系结构。良好实践知识。

你可以想象用var_dump() + ob_函数这样的方法来访问隐藏属性——但这只能说明使用一些体面的特性是多么可怕。

以及如何处理

不要这样使用Reflection。当然,在构建架构时不要指望这一点。这不是它应该用来做的事情。如果你想从外部访问你的属性——那么——很好,将它们声明为public

正确使用事物。这是唯一的出路。如果你不知道什么是正确的用法,那就去学吧。这是我们一直在做的事情。每一天。

public, protectedprivate令牌用于定义可见性属性,它并不意味着以任何方式提供安全性。

可见性用于区分:

  1. 你的公共接口,
  2. 暴露给类扩展的接口,或者
  3. 内部状态。

反射主要是作为提供诸如AOP、DIC、代理等功能的辅助工具;具体来说,它不是黑客的工具。使用您的代码的人可以简单地阅读它以获得他们想要的,不,编辑它以达到他们自己的"邪恶"目的。