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

Sud*_*ena 1 php oop

为了安全目的和封装我们有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>";
  }
Run Code Online (Sandbox Code Playgroud)

输出将是:

#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
Run Code Online (Sandbox Code Playgroud)

正如我们可以看到该类的所有成员是否Private, Protected or Public.那么OOP的概念在这里是什么?

PS:来自Shankar Damodaran的例子.

Alm*_* Do 6

TL; DR;

如果你做某事 - 这并不意味着你应该这样做

反射

这是旨在提供有关实体的元信息的东西,但它的实际用例是值得商榷的,并且几乎总是可以用某些东西代替.关键不是要说它不好,而是告诉 - 如果你想在你的架构中使用它,那么可能你有一个缺陷.

一种"去"的方式..

实际上,您可以在不使用的情况下访问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
Run Code Online (Sandbox Code Playgroud)

那么......那又怎样?每种语言功能都可以用于好的或坏的.我们称之为"良好做法"和"不良做法"(说实话,我很难记住globalPHP中的"良好实践" ,但这不属于这个问题).更多,在PHP中有很多你可以用错误的方式使用 - 它使语言变得困难 - 从某种意义上说,学习语言并不难,但很难正确使用它的所有功能,因为这需要坚实的建筑和良好的实践知识.

您可能会想象一种方法来访问隐藏属性甚至像var_dump()+ ob_函数这样的细节- 但这只能说明使用某些不错的功能是多么可怕.

以及如何处理它

不要Reflection以这种方式使用.在构建您的架构时,当然不要指望这一点.它不是应该使用它的东西.如果你想从外面访问你的房产 - 然后 - 罚款,请将它们声明为public.

只要正确使用东西.这是唯一的出路.如果你不知道什么是正确的用法 - 然后学习.这是我们一直在做的事情.每天.