programing

PHP> = 5.3 엄격 모드에서 오류를 생성하지 않고 객체에 속성을 추가하는 방법

nasanasas 2020. 11. 16. 21:37
반응형

PHP> = 5.3 엄격 모드에서 오류를 생성하지 않고 객체에 속성을 추가하는 방법


간단해야하는데 답을 찾을 수없는 것 같습니다 ....

$foo속성이없는 일반 stdClass 개체 가 있습니다. $bar아직 정의되지 않은 새 속성을 추가하고 싶습니다 . 이렇게하면 :

$foo = new StdClass();
$foo->bar = '1234';

엄격 모드의 PHP가 불평합니다.

이미 인스턴스화 된 객체에 속성을 추가하는 적절한 방법 (클래스 선언 외부)은 무엇입니까?

참고 : 솔루션이 stdClass 유형의 일반 PHP 개체와 함께 작동하기를 원합니다.

이 문제에 대한 약간의 배경. json 객체의 배열 인 json 문자열을 디코딩하고 있습니다. json_decode()StdClass 객체의 배열을 생성합니다. 이러한 개체를 조작하고 각 개체에 속성을 추가해야합니다.


객체에 속성을 절대적으로 추가해야하는 경우에는이를 배열로 캐스팅하고 속성을 새 배열 키로 추가 한 다음 다시 객체로 캐스팅 할 수 있다고 생각합니다. stdClass객체와 마주 치는 유일한 시간 은 배열을 객체로 캐스팅하거나 stdClass처음부터 객체 를 만들 때입니다 (물론 json_decode()무언가를 잊었을 어리석은 날!).

대신에:

$foo = new StdClass();
$foo->bar = '1234';

당신은 할 것 :

$foo = array('bar' => '1234');
$foo = (object)$foo;

또는 이미 기존 stdClass 객체가있는 경우 :

$foo = (array)$foo;
$foo['bar'] = '1234';
$foo = (object)$foo;

1 라이너로도 :

$foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) );

다음과 같이하십시오.

$foo = new StdClass();
$foo->{"bar"} = '1234';

이제 시도해보십시오.

echo $foo->bar; // should display 1234

디코딩 된 JSON을 편집하려면 객체 배열 대신 연관 배열로 가져 오십시오.

$data = json_decode($json, TRUE);

나는 항상 이런 식으로 사용합니다.

$foo = (object)null; //create an empty object
$foo->bar = "12345";

echo $foo->bar; //12345

매직 메서드 __Set 및 __get을 사용해야합니다. 간단한 예 :

class Foo
{
    //This array stores your properties
private $content = array();

public function __set($key, $value)
{
            //Perform data validation here before inserting data
    $this->content[$key] = $value;
    return $this;
}

public function __get($value)
{       //You might want to check that the data exists here
    return $this->$content[$value];
}

}

물론이 예제를 다음과 같이 사용하지 마십시오. 보안이 전혀 없습니다. :)

편집 : 귀하의 의견을 보았습니다. 여기에 반사 및 장식자를 기반으로 한 대안이 될 수 있습니다.

 class Foo
 {
private $content = array();
private $stdInstance;

public function __construct($stdInstance)
{
    $this->stdInstance = $stdInstance;
}

public function __set($key, $value)
{
    //Reflection for the stdClass object
    $ref = new ReflectionClass($this->stdInstance);
    //Fetch the props of the object

    $props = $ref->getProperties();

    if (in_array($key, $props)) {
        $this->stdInstance->$key = $value;
    } else {
        $this->content[$key] = $value;
    }
    return $this;
}

public function __get($value)
{
    //Search first your array as it is faster than using reflection
    if (array_key_exists($value, $this->content))
    {
        return $this->content[$value];
    } else {
        $ref = new ReflectionClass($this->stdInstance);

        //Fetch the props of the object
        $props = $ref->getProperties();

        if (in_array($value, $props)) {

        return $this->stdInstance->$value;
    } else {
        throw new \Exception('No prop in here...');
    }
}
 }
}

추신 : 나는 내 코드를 테스트하지 않았고 일반적인 아이디어 만 ...


최신 버전의 PHP인지는 모르겠지만 작동합니다. PHP 5.6을 사용하고 있습니다.

    <?php
    class Person
    {
       public $name;

       public function save()
       {
          print_r($this);
       }
    }

   $p = new Person;
   $p->name = "Ganga";
   $p->age = 23;

   $p->save();

이것이 결과입니다. save 메소드는 실제로 새 속성을 가져옵니다.

    Person Object
    (
       [name] => Ganga
       [age] => 23
    )

예, PHP 객체에 속성을 동적으로 추가 할 수 있습니다.

이것은 자바 스크립트에서 부분 객체를받을 때 유용합니다.

JAVASCRIPT 측 :

var myObject = { name = "myName" };
$.ajax({ type: "POST", url: "index.php",
    data: myObject, dataType: "json",
    contentType: "application/json;charset=utf-8"
}).success(function(datareceived){
    if(datareceived.id >= 0 ) { /* the id property has dynamically added on server side via PHP */ }
});

PHP 측 :

$requestString = file_get_contents('php://input');
$myObject = json_decode($requestString); // same object as was sent in the ajax call
$myObject->id = 30; // This will dynamicaly add the id property to the myObject object

또는 PHP로 채울 자바 스크립트에서 DUMMY 속성을 보내십시오.

참고 URL : https://stackoverflow.com/questions/11618349/how-to-add-property-to-object-in-php-5-3-strict-mode-without-generating-error

반응형