PHP에서 익명 객체 만들기
아시다시피 아래 코드와 같이 JavaScript로 익명 객체를 만드는 것은 쉽습니다.
var object = {
p : "value",
p1 : [ "john", "johnny" ] } ;
alert(object.p1[1]) ;
산출:
an alert is raised with value "johnny"
PHP의 경우에도 동일한 기술을 적용 할 수 있습니까? PHP에서 익명 객체를 만들 수 있습니까?
몇 년이 지났지 만 정보를 최신 상태로 유지해야한다고 생각합니다!
php-7에서는 익명 클래스를 만들 수 있으므로 다음과 같은 작업을 수행 할 수 있습니다.
<?php
class Foo {}
$child = new class extends Foo {};
var_dump($child instanceof Foo); // true
?>
RFC에서 자세한 내용을 읽을 수 있습니다 (허용됨). https://wiki.php.net/rfc/anonymous_classes
그러나 Javscript와 얼마나 유사한 지 잘 모르겠으므로 javascript와 php의 익명 클래스간에 약간의 차이가있을 수 있습니다.
편집하다:
게시 된 의견에서 다음은 현재 매뉴얼에 대한 링크입니다. http://php.net/manual/en/language.oop5.anonymous.php
"익명"은 객체에 대해 말할 때 올바른 용어가 아닙니다. "익명 타입의 객체"라고 말하는 것이 좋지만 PHP에는 적용되지 않습니다.
PHP의 모든 객체에는 클래스가 있습니다. "default"클래스는 다음 stdClass
과 같은 방식으로 객체를 만들 수 있습니다.
$obj = new stdClass;
$obj->aProperty = 'value';
보다 편리한 구문을 위해 배열을 객체 로 캐스트하는 이점을 활용할 수도 있습니다 .
$obj = (object)array('aProperty' => 'value');
print_r($obj);
그러나, 객체 배열을 캐스팅하는 것은 유효한 PHP 변수 이름없는 그 배열 키 "흥미로운"결과를 산출 할 가능성이 있음을 통보 - 예를 들어, 여기 내 대답이 키가 숫자로 시작하면 어떻게되는지 보여줍니다.
네 가능합니다! 이 간단한 PHP Anonymous Object 클래스를 사용합니다. 작동 방식 :
// define by passing in constructor
$anonim_obj = new AnObj(array(
"foo" => function() { echo "foo"; },
"bar" => function($bar) { echo $bar; }
));
$anonim_obj->foo(); // prints "foo"
$anonim_obj->bar("hello, world"); // prints "hello, world"
// define at runtime
$anonim_obj->zoo = function() { echo "zoo"; };
$anonim_obj->zoo(); // prints "zoo"
// mimic self
$anonim_obj->prop = "abc";
$anonim_obj->propMethod = function() use($anonim_obj) {
echo $anonim_obj->prop;
};
$anonim_obj->propMethod(); // prints "abc"
물론이 객체는 AnObj
클래스 의 인스턴스 이므로 실제로는 익명이 아니지만 JavaScript처럼 메소드를 즉석에서 정의 할 수 있습니다.
최근까지 이것은 객체를 즉석에서 생성 한 방법입니다.
$someObj = json_decode("{}");
그때:
$someObj->someProperty = someValue;
그러나 지금 나는 다음과 같이 간다.
$someObj = (object)[];
그런 다음 이전처럼 :
$someObj->someProperty = someValue;
물론 이미 속성과 값을 알고 있다면 언급 한대로 내부에서 설정할 수 있습니다.
$someObj = (object)['prop1' => 'value1','prop2' => 'value2'];
NB : 어떤 버전의 PHP가 작동하는지 잘 모르겠 기 때문에이를 염두에 두어야합니다. 그러나 첫 번째 접근 방식 (제작시 설정할 속성이없는 경우에도 짧음)은 json_encode / json_decode가있는 모든 버전에서 작동해야한다고 생각합니다.
If you wish to mimic JavaScript, you can create a class Object
, and thus get the same behaviour. Of course this isn't quite anonymous anymore, but it will work.
<?php
class Object {
function __construct( ) {
$n = func_num_args( ) ;
for ( $i = 0 ; $i < $n ; $i += 2 ) {
$this->{func_get_arg($i)} = func_get_arg($i + 1) ;
}
}
}
$o = new Object(
'aProperty', 'value',
'anotherProperty', array('element 1', 'element 2')) ;
echo $o->anotherProperty[1];
?>
That will output element 2. This was stolen from a comment on PHP: Classes and Objects.
Convert array to object:
$obj = (object) ['myProp' => 'myVal'];
If you want to create object (like in javascript) with dynamic properties, without receiving a warning of undefined property, when you haven't set a value to property
class stdClass {
public function __construct(array $arguments = array()) {
if (!empty($arguments)) {
foreach ($arguments as $property => $argument) {
if(is_numeric($property)):
$this->{$argument} = null;
else:
$this->{$property} = $argument;
endif;
}
}
}
public function __call($method, $arguments) {
$arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
if (isset($this->{$method}) && is_callable($this->{$method})) {
return call_user_func_array($this->{$method}, $arguments);
} else {
throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
}
}
public function __get($name){
if(property_exists($this, $name)):
return $this->{$name};
else:
return $this->{$name} = null;
endif;
}
public function __set($name, $value) {
$this->{$name} = $value;
}
}
$obj1 = new stdClass(['property1','property2'=>'value']); //assign default property
echo $obj1->property1;//null
echo $obj1->property2;//value
$obj2 = new stdClass();//without properties set
echo $obj2->property1;//null
Can this same technique be applied in case of PHP?
No - because javascript uses prototypes/direct declaration of objects - in PHP (and many other OO languages) an object can only be created from a class.
So the question becomes - can you create an anonymous class.
Again the answer is no - how would you instantiate the class without being able to reference it?
For one who wants a recursive object:
$o = (object) array(
'foo' => (object) array(
'sub' => '...'
)
);
echo $o->foo->sub;
From the PHP documentation, few more examples:
<?php
$obj1 = new \stdClass; // Instantiate stdClass object
$obj2 = new class{}; // Instantiate anonymous class
$obj3 = (object)[]; // Cast empty array to object
var_dump($obj1); // object(stdClass)#1 (0) {}
var_dump($obj2); // object(class@anonymous)#2 (0) {}
var_dump($obj3); // object(stdClass)#3 (0) {}
?>
$obj1 and $obj3 are the same type, but $obj1 !== $obj3. Also, all three will json_encode() to a simple JS object {}:
<?php
echo json_encode([
new \stdClass,
new class{},
(object)[],
]);
?>
Outputs:
[{},{},{}]
https://www.php.net/manual/en/language.types.object.php
참고URL : https://stackoverflow.com/questions/6384431/creating-anonymous-objects-in-php
'Programing' 카테고리의 다른 글
문자열이 직렬화되어 있는지 확인 하시겠습니까? (0) | 2020.07.03 |
---|---|
하스켈에서의 암기? (0) | 2020.07.03 |
Clojure의 맵 값에 함수 맵핑 (0) | 2020.07.03 |
이메일 뉴스 레터에 Google Plus (하나 또는 공유) 링크 추가 (0) | 2020.07.03 |
Java가 int를 바이트로 변환 할 때 이상한 행동? (0) | 2020.07.03 |