우리는 이런 컨텐트에서 병합하려면 꽂으십시오 ss+sp 한 두 개의 객체 및 PHP 5. 그들 사이에 다음 항목을 참조) 의 개념이 없기 때문에 하위 클래스 솔루션을 적용할 수 없습니다.
//We have this:
$objectA->a;
$objectA->b;
$objectB->c;
$objectB->d;
//We want the easiest way to get:
$objectC->a;
$objectC->b;
$objectC->c;
$objectC->d;
>. 만 포함할 경우 객체에는 필드 (no 메서드을), 이 작업:
$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);
또한 이 때 실제로 작동됨 객체에는 방법. (테스트됨 및 PHP 5.3-5.6)
기본 객체의 디스패치 매직 페이징됩니다 있는 다른 방법을 객체에는 만들 수 있습니다. # 39 의 you& here& 어떻게 처리할 수 있지만, 완전히 you& # 39; d '' _get 이해했소 apc® # 39, d 가 모든 관련 무시하려면 매직 있습니다. 구문 오류 찾기 때문에 그냥 you& # 39, ll 아마도 입력되었는지 it 끕니까 상단형 머리는요.
class Compositor {
private $obj_a;
private $obj_b;
public function __construct($obj_a, $obj_b) {
$this->obj_a = $obj_a;
$this->obj_b = $obj_b;
}
public function __get($attrib_name) {
if ($this->obj_a->$attrib_name) {
return $this->obj_a->$attrib_name;
} else {
return $this->obj_b->$attrib_name;
}
}
}
행운을 빕니다.
일반 객체에는 사용하는 것으로 안다 [스테드클레스 ()] 이 질문에 대한 답을 및 캐스팅 솔리드로 어레이에는 하지만 생각해봤죠 컴포지터 모함이야 멋지구리해요 대답. 그러나 일부 기능 향상 및 사용할 수 있다는 것을 느꼈다 누군가를 위해 도움이 될 것입니다.
기능:
코드:
class Compositor {
protected $composite = array();
protected $use_reference;
protected $first_precedence;
/**
* __construct, Constructor
*
* Used to set options.
*
* @param bool $use_reference whether to use a reference (TRUE) or to copy the object (FALSE) [default]
* @param bool $first_precedence whether the first entry takes precedence (TRUE) or last entry takes precedence (FALSE) [default]
*/
public function __construct($use_reference = FALSE, $first_precedence = FALSE) {
// Use a reference
$this->use_reference = $use_reference === TRUE ? TRUE : FALSE;
$this->first_precedence = $first_precedence === TRUE ? TRUE : FALSE;
}
/**
* Merge, used to merge multiple objects stored in an array
*
* This is used to *start* the merge or to merge an array of objects.
* It is not needed to start the merge, but visually is nice.
*
* @param object[]|object $objects array of objects to merge or a single object
* @return object the instance to enable linking
*/
public function & merge() {
$objects = func_get_args();
// Each object
foreach($objects as &$object) $this->with($object);
// Garbage collection
unset($object);
// Return $this instance
return $this;
}
/**
* With, used to merge a singluar object
*
* Used to add an object to the composition
*
* @param object $object an object to merge
* @return object the instance to enable linking
*/
public function & with(&$object) {
// An object
if(is_object($object)) {
// Reference
if($this->use_reference) {
if($this->first_precedence) array_push($this->composite, $object);
else array_unshift($this->composite, $object);
}
// Clone
else {
if($this->first_precedence) array_push($this->composite, clone $object);
else array_unshift($this->composite, clone $object);
}
}
// Return $this instance
return $this;
}
/**
* __get, retrieves the psudo merged object
*
* @param string $name name of the variable in the object
* @return mixed returns a reference to the requested variable
*
*/
public function & __get($name) {
$return = NULL;
foreach($this->composite as &$object) {
if(isset($object->$name)) {
$return =& $object->$name;
break;
}
}
// Garbage collection
unset($object);
return $return;
}
}
사용법:
$obj = new Compositor(use_reference, first_precedence);
$obj->merge([object $object [, object $object [, object $...]]]);
$obj->with([object $object]);
예:
$obj1 = new stdClass();
$obj1->a = 'obj1:a';
$obj1->b = 'obj1:b';
$obj1->c = 'obj1:c';
$obj2 = new stdClass();
$obj2->a = 'obj2:a';
$obj2->b = 'obj2:b';
$obj2->d = 'obj2:d';
$obj3 = new Compositor();
$obj3->merge($obj1, $obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj2:a, obj2:b, obj1:c, obj2:d
$obj1->c;
$obj3 = new Compositor(TRUE);
$obj3->merge($obj1)->with($obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj1:a, obj1:b, obj1:c, obj2:d
$obj1->c = 'obj1:c';
$obj3 = new Compositor(FALSE, TRUE);
$obj3->with($obj1)->with($obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj1:a, obj1:b, #obj1:c, obj2:d
$obj1->c = 'obj1:c';
유지할 수 있는 솔루션을 모두 론젝트스 병합되었습니다 수 있는 방법 및 특성 (properties) 을 만드는 것이 연결자 클래스
아무 것도 할 수 있는 객체에는 _construct
액세스만 _call 사용하여 임의의 방법
이스체스 _get 사용하여 모든 속성
class combinator{
function __construct(){
$this->melt = array_reverse(func_get_args());
// array_reverse is to replicate natural overide
}
public function __call($method,$args){
forEach($this->melt as $o){
if(method_exists($o, $method)){
return call_user_func_array([$o,$method], $args);
//return $o->$method($args);
}
}
}
public function __get($prop){
foreach($this->melt as $o){
if(isset($o->$prop))return $o->$prop;
}
return 'undefined';
}
}
사용하는 단순한
class c1{
public $pc1='pc1';
function mc1($a,$b){echo __METHOD__." ".($a+$b);}
}
class c2{
public $pc2='pc2';
function mc2(){echo __CLASS__." ".__METHOD__;}
}
$comb=new combinator(new c1, new c2);
$comb->mc1(1,2);
$comb->non_existing_method(); // silent
echo $comb->pc2;
이 '클래스' 는 현재 기존 reference 스토리지로는 분리하십시오 exchange \ArrayObject 가능성이 크다. 이를 위해 두 개의 않했노라 간편한 방법: '에스창어리 ()' 와 '게타이코프 ()'. () 는 단순한 '일반' 의 함께 제공된 객체에는 미삭 array_merge 라이로비치 '의 공개 속성:
class MergeBase extends ArrayObject
{
public final function merge( Array $toMerge )
{
$this->exchangeArray( array_merge( $this->getArrayCopy(), $toMerge ) );
}
}
다음과 같이 간편한 사용법
$base = new MergeBase();
$base[] = 1;
$base[] = 2;
$toMerge = [ 3,4,5, ];
$base->merge( $toMerge );
꼭 이래야겠어요 가는 첫 번째 객체에는 링크뿐 붙여넣습니다 객체에는 속성 중 하나이다. 만약 두 번째 객체인지 결과를 함수 또는 메서드를 사용하여 참조입니다. 예:
//Not the result of a method
$obj1->extra = new Class2();
//The result of a method, for instance a factory class
$obj1->extra =& Factory::getInstance('Class2');
function copy_properties($from, $to, $fields = null) {
// copies properties/elements (overwrites duplicates)
// can take arrays or objects
// if fields is set (an array), will only copy keys listed in that array
// returns $to with the added/replaced properties/keys
$from_array = is_array($from) ? $from : get_object_vars($from);
foreach($from_array as $key => $val) {
if(!is_array($fields) or in_array($key, $fields)) {
if(is_object($to)) {
$to->$key = $val;
} else {
$to[$key] = $val;
}
}
}
return($to);
}
코드의 크레딧보다 그들위에 댁이라면 혼자:)
이것은 함수 객체를 플랫화할 될 또는 배열입니다. 이 키는 고유하도록 중인 경우에만 사용해야 합니다. 키 같은 이름의 경우 그들은 덮어씁니다. 이 클래스에서 및 교체, Functions" " 배치하십시오 합니다. 이름이 해당 클래스의. 즐기세요.
function flatten($array, $preserve_keys=1, &$out = array(), $isobject=0) {
# Flatten a multidimensional array to one dimension, optionally preserving keys.
#
# $array - the array to flatten
# $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
# $out - internal use argument for recursion
# $isobject - is internally set in order to remember if we're using an object or array
if(is_array($array) || $isobject==1)
foreach($array as $key => $child)
if(is_array($child))
$out = Functions::flatten($child, $preserve_keys, $out, 1); // replace "Functions" with the name of your class
elseif($preserve_keys + is_string($key) > 1)
$out[$key] = $child;
else
$out[] = $child;
if(is_object($array) || $isobject==2)
if(!is_object($out)){$out = new stdClass();}
foreach($array as $key => $child)
if(is_object($child))
$out = Functions::flatten($child, $preserve_keys, $out, 2); // replace "Functions" with the name of your class
elseif($preserve_keys + is_string($key) > 1)
$out->$key = $child;
else
$out = $child;
return $out;
}
이 스니핏을 의 코드는 해당 데이터를 재귀적으로 변환 없이 한 가지 종류의 (어레이나 객체에는) 네스트된 포리치 반복됩니다. 이를 통해 희망을 누군가!
다시 한 번 객체가 어레이당 형식으로 변환하여 array_merge 객체에는 할 경우 사용할 수 있습니다.
abstract class Util {
public static function object_to_array($d) {
if (is_object($d))
$d = get_object_vars($d);
return is_array($d) ? array_map(__METHOD__, $d) : $d;
}
public static function array_to_object($d) {
return is_array($d) ? (object) array_map(__METHOD__, $d) : $d;
}
}
절차적 운행에서어떠한
function object_to_array($d) {
if (is_object($d))
$d = get_object_vars($d);
return is_array($d) ? array_map(__FUNCTION__, $d) : $d;
}
function array_to_object($d) {
return is_array($d) ? (object) array_map(__FUNCTION__, $d) : $d;
}
모든 크레딧보다 마이그레이션된: 제이슨 오클리