質問

文字列に基づいて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-&gt; {$ obj-&gt; Name}中括弧は、変数変数のようにプロパティをラップします。

これはトップ検索でした。しかし、$ thisを使用していた私の質問は解決しませんでした。私の状況では、中括弧を使用することも役立ちました...

Code Igniterがインスタンスを取得する例

親クラスインスタンスを持つ何かと呼ばれるソースライブラリクラス内

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

親インスタンスも含む別のクラスからソースを取得する必要があるライブラリクラス

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

この質問には答えがあるかもしれませんが、PHP 7へのこれらの移行を見たい場合があります

後方互換性のない変更

ソース: php.net

追加として: このようにして、そうでなければ使用できない名前のプロパティにアクセスできます

$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-&gt; Bar-&gt; baz、または$ Foo-&gt; baz、または$ Foo-&gt; Bar-&gt; Baz-&gt; daveを検索するには、$ pathは次のような文字列です「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」チェックをそれぞれ__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);

編集の理由: 前:evalを使用(悪) 後:評価なし。この言語では古い。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top