1

他の言語の便利な機能の 1 つは、プロパティの get メソッドと set メソッドを作成できることです。この機能を PHP で複製する良い方法を見つけようとして、私はこれに出くわしました: http://www.php.net/manual/en/language.oop5.magic.php#98442

そのクラスの内訳は次のとおりです。

<?php

class ObjectWithGetSetProperties {

    public function __get($varName) {
        if (method_exists($this,$MethodName='get_'.$varName)) {
            return $this->$MethodName();
        } else {
            trigger_error($varName.' is not avaliable .',E_USER_ERROR);
        }
    }

    public function __set($varName,$value) {
        if (method_exists($this,$MethodName='set_'.$varName)) {
            return $this->$MethodName($value);
        } else {
            trigger_error($varName.' is not avaliable .',E_USER_ERROR);
        }
    }

}

?>

私の計画は、このクラスを拡張し、この拡張クラスで適切なget_someproperty()andを定義することでした。set_someproperty()

<?php
class SomeNewClass extends ObjectWithGetSetProperties {
    protected $_someproperty;
    public function get_someproperty() {
        return $this->_someproperty;
    }
}
?>

問題は、 の基底クラスが のObjectWithGetSetPropertiesメソッドを認識できないことget_someproperty()ですSomeNewClass。「キーが利用できません」というエラーが常に表示されます。

これを解決して、の基本クラスが機能するようにする方法はありますか、または各クラスでそれらと魔法のメソッドObjectWithGetSetPropertiesを作成する必要がありますか?__get()__set()

4

4 に答える 4

5

is_callable代わりに試してください。コードフラグメントの例:

<?php
date_default_timezone_set("America/Edmonton");
class A {
    protected $_two="goodbye";
    protected $_three="bye";
    protected $_four="adios";
    public function __get($name) {
        if (is_callable(array($this,$m="get_$name"))) {
            return $this->$m();
        }
        trigger_error("Doh $name not found.");
    }
    public function get_two() {
        return $this->_two;
    }
}
class B extends A {
    protected $_one="hello";
    protected $_two="hi";
    protected $_three="hola";
    public function get_one() {
        return $this->_one;
    }
    public function get_two() {
        return $this->_two;
    }
    public function get_three() {
        return $this->_three;
    }
    public function get_four() {
        return $this->_four;
    }
}

$a=new a();
echo $a->one."<br />";//Doh one not found.
echo $a->two."<br />";//goodbye
echo $a->three."<br />";//Doh three not found.
echo $a->four."<br />";//Doh four not found.
$b=new b();
echo $b->one."<br />";//hello
echo $b->two."<br />";//hi
echo $b->three."<br />";//hola
echo $b->four."<br />";//adios
?>

B(オーバーライドする場所を表示するように更新A)

于 2011-02-07T17:10:03.340 に答える
3

これは十分に文書化されていませんが (コメントにいくつかの言及があります)、method_exists()実際には現在のクラスにメソッドが存在するかどうかのみをチェックします。

ただし、代わりに使用できますis_callable()。また、メソッドが存在するだけでなく、実際に呼び出しが許可されていることも確認します。

 if (  is_callable(array($this, $varName))  ) {
     ...
于 2011-02-07T17:10:43.763 に答える
0

あなたの例では、次の$_somepropertyようにプロパティを宣言する必要があります

class SomeNewClass extends ObjectWithGetSetProperties {
    protected $_someproperty;
    public function get_someproperty() {
        return $this->_someproperty;
    }
}
于 2011-02-07T17:10:30.860 に答える