문자열별로 PHP 클래스 속성을 얻으십시오
-
03-07-2019 - |
문제
문자열을 기준으로 PHP에서 속성을 어떻게 얻습니까? 나는 그것을 부를 것이다 magic
. 그래서 무엇입니까 magic
?
$obj->Name = 'something';
$get = $obj->Name;
같을 것 같아 ...
magic($obj, 'Name', 'something');
$get = magic($obj, 'Name');
해결책
이와 같이
<?php
$prop = 'Name';
echo $obj->$prop;
또는 클래스를 제어 할 수있는 경우 ArrayAccess 인터페이스하고 그냥이 작업을 수행하십시오
echo $obj['Name'];
다른 팁
중간 변수를 만들지 않고 속성에 액세스하려면 {}
표기법:
$something = $object->{'something'};
예를 들어 다음과 같은 루프에 속성 이름을 작성할 수 있습니다.
for ($i = 0; $i < 5; $i++) {
$something = $object->{'something' . $i};
// ...
}
당신이 묻는 것은 호출됩니다 변수 변수. 문자열을 변수에 저장하고 그렇게 액세스하기 만하면됩니다.
$Class = 'MyCustomClass';
$Property = 'Name';
$List = array('Name');
$Object = new $Class();
// All of these will echo the same property
echo $Object->$Property; // Evaluates to $Object->Name
echo $Object->{$List[0]}; // Use if your variable is in an array
이 같은? 테스트하지는 않았지만 잘 작동해야합니다.
function magic($obj, $var, $value = NULL)
{
if($value == NULL)
{
return $obj->$var;
}
else
{
$obj->$var = $value;
}
}
속성 이름을 변수에 저장하고 변수를 사용하여 속성에 액세스하십시오. 이와 같이:
$name = 'Name';
$obj->$name = 'something';
$get = $obj->$name;
간단합니다. $ obj-> {$ obj-> name} Curly Brackets는 변수 변수와 매우 유사한 속성을 감싸게됩니다.
이것은 최고의 검색이었습니다. 그러나 내 질문을 해결하지 못했습니다. Curly Bracket을 사용하는 내 상황의 경우도 도움이되었습니다.
코드 점화기의 예제 인스턴스를 얻습니다
상위 클래스 인스턴스와 함께하는 소스 라이브러리 클래스에서
$this->someClass='something';
$this->someID=34;
부모 인스턴스와 함께 다른 클래스에서 소스를 소스 해야하는 도서관 클래스
echo $this->CI->{$this->someClass}->{$this->someID};
추가로 :이 방법으로는 사용할 수없는 이름으로 속성에 액세스 할 수 있습니다.
$x = new StdClass;$ prop = 'A B'; $ x-> $ prop = 1; $ x-> { 'x y'} = 2; var_dump ($ x);
object(stdClass)#1 (2) { ["a b"]=> int(1) ["x y"]=> int(2) }(그렇게해야 할 경우가 아니라면).
더 멋진 일을하고 싶다면 살펴 봐야합니다. 반사
다른 사람이 알려지지 않은 깊이의 깊은 속성을 찾고자하는 경우, 나는 모든 어린이의 모든 알려진 속성을 통해 반복 할 필요없이 아래를 생각해 냈습니다.
예를 들어, $ foo-> bar-> baz 또는 $ foo-> baz 또는 $ foo-> bar-> baz-> dave를 찾으려면 $ 경로는 'foo/bar/baz'와 같은 문자열입니다.
public function callModule($pathString, $delimiter = '/'){
//split the string into an array
$pathArray = explode($delimiter, $pathString);
//get the first and last of the array
$module = array_shift($pathArray);
$property = array_pop($pathArray);
//if the array is now empty, we can access simply without a loop
if(count($pathArray) == 0){
return $this->{$module}->{$property};
}
//we need to go deeper
//$tmp = $this->Foo
$tmp = $this->{$module};
foreach($pathArray as $deeper){
//re-assign $tmp to be the next level of the object
// $tmp = $Foo->Bar --- then $tmp = $Bar->baz
$tmp = $tmp->{$deeper};
}
//now we are at the level we need to be and can access the property
return $tmp->{$property};
}
그런 다음 다음과 같은 것을 호출하십시오.
$propertyString = getXMLAttribute('string'); // '@Foo/Bar/baz'
$propertyString = substr($propertyString, 1);
$moduleCaller = new ModuleCaller();
echo $moduleCaller->callModule($propertyString);
여기 내 시도가 있습니다. 그것은 몇 가지 일반적인 '어리 석음'수표가 내장되어있어 사용할 수없는 멤버를 설정하거나 얻지 못하게합니다.
해당 'Property_Exists'검사를 각각 __ 세트로 옮기고 __get로 이동하여 Magic () 내에서 직접 호출 할 수 있습니다.
<?php
class Foo {
public $Name;
public function magic($member, $value = NULL) {
if ($value != NULL) {
if (!property_exists($this, $member)) {
trigger_error('Undefined property via magic(): ' .
$member, E_USER_ERROR);
return NULL;
}
$this->$member = $value;
} else {
if (!property_exists($this, $member)) {
trigger_error('Undefined property via magic(): ' .
$member, E_USER_ERROR);
return NULL;
}
return $this->$member;
}
}
};
$f = new Foo();
$f->magic("Name", "Something");
echo $f->magic("Name") , "\n";
// error
$f->magic("Fame", "Something");
echo $f->magic("Fame") , "\n";
?>
이 기능이하는 일은 자녀의 모든 클래스에 속성이 존재하는지 확인하고 그렇다면 값을 얻는 경우 널을 반환합니다. 이제 속성은 선택적이고 역동적입니다.
/**
* check if property is defined on this class or any of it's childes and return it
*
* @param $property
*
* @return bool
*/
private function getIfExist($property)
{
$value = null;
$propertiesArray = get_object_vars($this);
if(array_has($propertiesArray, $property)){
$value = $propertiesArray[$property];
}
return $value;
}
용법:
const CONFIG_FILE_PATH_PROPERTY = 'configFilePath';
$configFilePath = $this->getIfExist(self::CONFIG_FILE_PATH_PROPERTY);
$classname = "myclass";
$obj = new $classname($params);
$variable_name = "my_member_variable";
$val = $obj->$variable_name; //do care about the level(private,public,protected)
$func_name = "myFunction";
$val = $obj->$func_name($parameters);
편집 이유 : 전 : ATAVE (evit) 사용 : 전혀 평가가 없습니다. 이 언어로 나이가 들었습니다.