programing

문자열로 PHP 클래스 속성 가져오기

yoursource 2022. 10. 2. 12:27
반응형

문자열로 PHP 클래스 속성 가져오기

문자열을 기반으로 PHP 속성을 가져오려면 어떻게 해야 합니까?전화할게magic그럼 뭐라는 거야?magic?

$obj->Name = 'something';
$get = $obj->Name;

뭐랄까...

magic($obj, 'Name', 'something');
$get = magic($obj, 'Name');

이것처럼.

<?php

$prop = 'Name';

echo $obj->$prop;

또는 클래스를 제어할 수 있는 경우 Array Access 인터페이스를 구현하고 이 작업을 수행합니다.

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;

이 질문에 대한 답변이 있을 수 있지만 PHP 7로의 이행을 볼 수 있습니다.

역호환성 변화

출처 : php.net

단순합니다. $obj->{$obj->Name}는 변수 변수와 마찬가지로 속성을 콜 괄호로 묶습니다.

이건 최고의 검색이었어하지만 $this를 사용한 제 질문은 해결되지 않았습니다.내 사정은 곱슬 괄호를 사용하는 것도 도움이 되었다...

Code Igniter get instance를 사용한 예

부모 클래스 인스턴스라는 소스 라이브러리 클래스의 것

$this->someClass='something';
$this->someID=34;

부모 인스턴스와 함께 다른 클래스에서 소스를 얻을 필요가 있는 라이브러리 클래스

echo $this->CI->{$this->someClass}->{$this->someID};

추가 사항으로서:이렇게 하지 않으면 사용할 수 없는 이름으로 속성에 액세스할 수 있습니다.

$x = 새로운 표준 클래스;

$prop = 'a b';$x->$prop = 1;$x->{'x y'} = 2;var_var_variacx);

object(stdClass) #1 (2) {["a b"]=>int(1)["xy"]=>int(2)}
(not that you should, but in case you have to).
If you want to do even fancier stuff you should look into 반사

만약 다른 누군가가 깊이를 알 수 없는 깊은 속성을 찾고 싶어한다면, 나는 모든 아이들의 알려진 속성을 반복할 필요 없이 다음과 같은 것을 생각해냈다.

예를 들어, 찾으려면$foo->Bar->baz->bam오브젝트 지정($foo) 및 "Baz->bam"과 같은 문자열입니다.

trait PropertyGetter {
    public function getProperty($pathString, $delimiter = '->') {

        //split the string into an array
        $pathArray = explode($delimiter, $pathString);

        //get the first and last of the array
        $first = array_shift($pathArray);
        $last = array_pop($pathArray);

        //if the array is now empty, we can access simply without a loop
        if(count($pathArray) == 0){
            return $this->{$first}->{$last};
        }

        //we need to go deeper
        //$tmp = $this->Foo
        $tmp = $this->{$first};

        foreach($pathArray as $deeper) {
            //re-assign $tmp to be the next level of the object
            // $tmp = $Foo->Bar --- then $tmp = $tmp->baz
            $tmp = $tmp->{$deeper};
        }

        //now we are at the level we need to be and can access the property
        return $tmp->{$last};

    }
}

그런 다음 다음과 같이 전화하십시오.

$foo = new SomeClass(); // this class imports PropertyGetter trait
echo $foo->getProperty("bar->baz->bam");

제 시도는 이렇습니다.일반적인 '우둔한' 체크 기능이 내장되어 있어 사용할 수 없는 멤버를 설정하거나 구하려고 하지 않습니다.

이러한 'property_exists' 체크를 각각 __set 및 __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";

?>

이 함수는 해당 자녀의 이 클래스에 속성이 있는지 확인하고, 그렇지 않으면 값을 얻으면 null을 반환합니다.이제 속성은 옵션이고 역동적입니다.

/**
 * 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);

편집 이유: 이전: 이후 평가(악) 사용: 전혀 평가하지 않습니다. 이 언어에 익숙하기 때문입니다.

언급URL : https://stackoverflow.com/questions/804850/get-php-class-property-by-string

반응형