سؤال

public static function __get($value)

لا يعمل، وحتى لو فعل ذلك، يحدث ذلك فأنا بحاجة بالفعل إلى Magic __ Getter خصائص مثيل في نفس الفصل.

ربما هذا هو نعم أو لا سؤال، لذلك، فمن الممكن؟

هل كانت مفيدة؟

المحلول

لا، لم يكن ممكنا.

نقلا عن صفحة دليل __et :

يعمل تحميل الأعضاء فقط في سياق كائن. لن يتم تشغيل هذه الأساليب السحرية في سياق ثابت. لذلك لا يمكن إعلان هذه الأساليب ثابتة.


في PHP 5.3، __callStatic تمت إضافة ؛ ولكن لا يوجد __getStatic ولا __setStatic بعد ؛ حتى لو عدت / ترميزها غالبا ما تعود إلى قائمة PHP Internals @.

هناك حتى طلب تعليقات: دروس ثابتة ل PHP
ولكن، لا يزال، غير منفذ (بعد ؟ )

نصائح أخرى

ربما ما زال شخص ما بحاجة إلى هذا:

static public function __callStatic($method, $args) {

  if (preg_match('/^([gs]et)([A-Z])(.*)$/', $method, $match)) {
    $reflector = new \ReflectionClass(__CLASS__);
    $property = strtolower($match[2]). $match[3];
    if ($reflector->hasProperty($property)) {
      $property = $reflector->getProperty($property);
      switch($match[1]) {
        case 'get': return $property->getValue();
        case 'set': return $property->setValue($args[0]);
      }     
    } else throw new InvalidArgumentException("Property {$property} doesn't exist");
  }
}

لطيفة جدا mbrzuchalski. ولكن يبدو أنه يعمل فقط على المتغيرات العامة. ما عليك سوى تغيير المفتاح الخاص بك إلى هذا للسماح له بالوصول إلى تلك الخاصة / المحمية:

switch($match[1]) {
   case 'get': return self::${$property->name};
   case 'set': return self::${$property->name} = $args[0];
}

وربما تريد تغيير if بيان للحد من المتغيرات التي يمكن الوصول إليها، وإلا فإنها ستهزم الغرض من وجودها خاصة أو محمية.

if ($reflector->hasProperty($property) && in_array($property, array("allowedBVariable1", "allowedVariable2"))) {...)

لذلك على سبيل المثال، لدي فئة مصممة لسحب البيانات المختلفة بالنسبة لي من الخادم البعيد باستخدام وحدة نمط الكمثرى SSH، وأريد ذلك إجراء بعض الافتراضات حول الدليل الهدف بناء على الخادم الذي يطلب منه إلقاء نظرة عليه. نسخة مشبعة من طريقة mbrzuchalski هي مثالية لذلك.

static public function __callStatic($method, $args) {
    if (preg_match('/^([gs]et)([A-Z])(.*)$/', $method, $match)) {
        $reflector = new \ReflectionClass(__CLASS__);
        $property = strtolower($match[2]). $match[3];
        if ($reflector->hasProperty($property)) {
            if ($property == "server") {
                $property = $reflector->getProperty($property);
                switch($match[1]) {
                    case 'set':
                        self::${$property->name} = $args[0];
                        if ($args[0] == "server1") self::$targetDir = "/mnt/source/";
                        elseif($args[0] == "server2") self::$targetDir = "/source/";
                        else self::$targetDir = "/";
                    case 'get': return self::${$property->name};
                }
            } else throw new InvalidArgumentException("Property {$property} is not publicly accessible.");
        } else throw new InvalidArgumentException("Property {$property} doesn't exist.");
    }
}

جرب هذا:

class nameClass{
    private static $_sData = [];
    private static $object = null;
    private $_oData = [];

    public function __construct($data=[]){
        $this->_oData = $data;
    }

    public static function setData($data=[]){
        self::$_sData = $data;
    }

    public static function Data(){
        if( empty( self::$object ) ){
            self::$object = new self( self::$_sData ); 
        }
        return self::$object;
    }

    public function __get($key) {
        if( isset($this->_oData[$key] ){
            return $this->_oData[$key];
        }
    }

    public function __set($key, $value) {
        $this->_oData[$key] = $value;
    }
}

nameClass::setData([
    'data1'=>'val1',
    'data2'=>'val2',
    'data3'=>'val3',
    'datan'=>'valn'
]);

nameClass::Data()->data1 = 'newValue';
echo(nameClass::Data()->data1);
echo(nameClass::Data()->data2);

أيضا، يمكنك الحصول على خصائص ثابتة تصل إليهم مثل خصائص الأعضاء، باستخدام __Get ():

class ClassName {    
    private static $data = 'smth';

    function __get($field){
        if (isset($this->$field)){
            return $this->$field;
        }
        if(isset(self::$$field)){  
            return self::$$field;  // here you can get value of static property
        }
        return NULL;
    }
}

$obj = new ClassName();
echo $obj->data; // "smth"

الجمع بين __callStatic و call_user_func أو call_user_func_array يمكن أن تمنح الوصول إلى الخصائص الثابتة في فئة PHP

مثال:

class myClass {

    private static $instance;

    public function __construct() {

        if (!self::$instance) {
            self::$instance = $this;
        }

        return self::$instance;
    }

    public static function __callStatic($method, $args) {

        if (!self::$instance) {
            new self();
        }

        if (substr($method, 0, 1) == '$') {
            $method = substr($method, 1);
        }

        if ($method == 'instance') {
            return self::$instance;
        } elseif ($method == 'not_exist') {
            echo "Not implemented\n";
        }
    }

    public function myFunc() {
        echo "myFunc()\n";
    }

}

// Getting $instance
$instance = call_user_func('myClass::$instance');
$instance->myFunc();

// Access to undeclared
call_user_func('myClass::$not_exist');
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top