복붙노트

PHP에서 객체의 보호 된 속성을 얻는 방법

PHP

PHP에서 객체의 보호 된 속성을 얻는 방법

내가 얻고 싶은 보호 속성이있는 객체가 있습니다. 객체는 다음과 같이 보입니다.

Fields_Form_Element_Location Object
(
[helper] => formText
[_allowEmpty:protected] => 1
[_autoInsertNotEmptyValidator:protected] => 1
[_belongsTo:protected] => 


[_description:protected] => 
[_disableLoadDefaultDecorators:protected] => 
[_errorMessages:protected] => Array
    (
    )

[_errors:protected] => Array
    (
    )
[_isErrorForced:protected] => 
[_label:protected] => Current City


[_value:protected] => 93399
[class] => field_container field_19 option_1 parent_1
)

개체의 value 속성을 가져오고 싶습니다. $ obj -> _ value 또는 $ obj -> value를 시도하면 에러가 발생합니다. PHP 리플렉션 클래스를 사용하여 솔루션을 검색하고 발견했습니다. 그것은 내 로컬 서버에서 작동하지만 PHP는 5.2.17 버전이므로이 함수를 사용할 수 없습니다. 그래서 어떤 해결책을 얻으려면 그러한 자산을 얻는가?

해결법

  1. ==============================

    1.가시성 장에서 설명하는대로 "보호 된"의미입니다.

    가시성 장에서 설명하는대로 "보호 된"의미입니다.

    외부에서 부동산에 액세스해야하는 경우 다음 중 하나를 선택하십시오.

    원래 클래스를 수정하고 싶지 않으면 (타사 라이브러리이므로 엉망으로 만들고 싶지는 않습니다.) 원래 클래스를 확장하는 사용자 정의 클래스를 만듭니다.

    class MyFields_Form_Element_Location extends Fields_Form_Element_Location{
    }
    

    ... getter / setter를 거기에 추가하십시오.

  2. ==============================

    2.ReflectionClass를 사용하는 방법에 대한 간단한 예제가있다.

    ReflectionClass를 사용하는 방법에 대한 간단한 예제가있다.

    function accessProtected($obj, $prop) {
      $reflection = new ReflectionClass($obj);
      $property = $reflection->getProperty($prop);
      $property->setAccessible(true);
      return $property->getValue($obj);
    }
    

    나는 당신이 5.2로 제한되었다고 말한 것을 알고 있습니다. 그러나 그것은 2 년 전이었습니다. 5.5는 가장 오래된 지원 버전이고 현대 버전을 가진 사람들을 돕기를 희망합니다.

  3. ==============================

    3.오브젝트는 (연관) 배열로 타입 변환 될 수 있고, 보호 된 멤버는 chr (0). *. chr (0) 접두어가 붙은 키를 가지고 있습니다 (여기 @ fardelian의 설명 참조). 이 배치되지 않은 기능을 사용하여 "노출 자"를 작성할 수 있습니다.

    오브젝트는 (연관) 배열로 타입 변환 될 수 있고, 보호 된 멤버는 chr (0). *. chr (0) 접두어가 붙은 키를 가지고 있습니다 (여기 @ fardelian의 설명 참조). 이 배치되지 않은 기능을 사용하여 "노출 자"를 작성할 수 있습니다.

    function getProtectedValue($obj,$name) {
      $array = (array)$obj;
      $prefix = chr(0).'*'.chr(0);
      return $array[$prefix.$name];
    }
    

    또는 직렬화 된 문자열에서 값을 구문 분석 할 수 있습니다. 보호 된 멤버가 동일한 접두어를 사용하는 것으로 보입니다 (php 5.2에서 변경되지 않았 으면합니다).

  4. ==============================

    4.게터와 세터를 추가하지 않고 수업을 꾸미고 싶다면 ....

    게터와 세터를 추가하지 않고 수업을 꾸미고 싶다면 ....

    PHP 7에서는 closure에 call ($ obj) 메소드 (old bindTo보다 빠름)를 추가하여 함수를 호출 할 수있게하여 $ this 변수가 클래스 내 에서처럼 전체 권한으로 작동하도록합니다.

     //test class with restricted properties
     class test{
        protected $bar="protected bar";
        private $foo="private foo";
        public function printProperties(){
            echo $this->bar."::".$this->foo;   
         }
     }
    
    $testInstance=new test();
    //we can change or read the restricted properties by doing this...
    $change=function(){
        $this->bar="I changed bar";
        $this->foo="I changed foo";
    };
    $change->call($testInstance);
    $testInstance->printProperties();
    //outputs I changed bar::I changed foo in php 7.0 
    
  5. ==============================

    5.원래 클래스를 수정할 수없고 확장 할 수도없는 경우 ReflectionProperty 인터페이스를 사용할 수 있습니다.

    원래 클래스를 수정할 수없고 확장 할 수도없는 경우 ReflectionProperty 인터페이스를 사용할 수 있습니다.

    phptoolcase 라이브러리는 이것을위한 편리한 메소드를 가지고 있습니다 :

    $value = PtcHandyMan::getProperty( $your_object , ‘propertyName’);
    

    싱글 톤 클래스의 정적 속성 :

    $value = PtcHandyMan::getProperty( ‘myCLassName’ , ‘propertyName’);
    

    이 도구는 http://phptoolcase.com/guides/ptc-hm-guide.html에서 찾을 수 있습니다.

  6. ==============================

    6.

      $propGetter = Closure::bind(  function($prop){return $this->$prop;}, $element['field_text']['#object'], $element['field_text']['#object'] );
      drupal_set_message('count='.count($propGetter('hostEntity')->field_captioned_carousel['und']));
    
  7. from https://stackoverflow.com/questions/20334355/how-to-get-protected-property-of-object-in-php by cc-by-sa and MIT license