Dinamik PHP sınıfları örnek değişkenleri oluşturma

5 Cevap php

Ben bu önemsiz bir soru ama bir PHP sınıfı eğer emin değilim:

MyClass:

class MyClass {
   public $var1;
   public $var2;

    constructor() { ... }

    public method1 () {

    // Dynamically create an instance variable
         $this->var3 = "test"; // Public....?


    }
}

Main:

$test = new MyClass();
$test->method1();
echo $test->var3; // Would return "test"

Bu çalışır mı? Bunu nasıl işe almak istiyorsunuz? Ps. Ben hızlı bir şekilde bu yüzden sınıf kurma veya yöntemlerini çağırarak yapılan hataları lütfen dikkate almayınız bu yazdı!

EDIT What about making these instance variables that I create private??

EDIT 2 Thanks all for responding - Everyone is right - I should have just tested it out myself, but I had an exam the next morning and had this thought while studying that I wanted to check to see if it worked. People keep suggesting that its bad OOP - maybe but it does allow for some elegant code. Let me explain it a bit and see if you still think so. Here's what I came up with:

//PHP User Model: 

class User {
    constructor() { ... }

    public static find($uid) {
         $db->connect(); // Connect to the database

         $sql = "SELECT STATEMENT ...WHERE id=$uid LIMIT 1;";
    	 $result = $db->query($sql); // Returns an associative array

         $user = new User();

    	 foreach ($result as $key=>$value)
    		$user->$$key = $value; //Creates a public variable of the key and sets it to value

         $db->disconnect();
    }
}

//PHP Controller:

function findUser($id) {

    $User = User::find($id);

    echo $User->name;
    echo $User->phone;
    //etc...

}

Eğer veritabanında ne olduğunu bilmek zorunda ben sadece bir ilişkisel dizi koymak olabilir ama doğru anlamlı Bu diziyi bir şey isim olamaz (çirkin yani $ user-> data ['name'] ...). Her iki şekilde bu yüzden gerçekten argüman ne olduğunu anlamıyorum onun kafa karıştırıcı, özellikle de hata ayıklama için sadece var dökümü nesneler yapabilirsiniz.

Thanks, Matt Mueller

5 Cevap

Evet bu gerçekten çalışacak. Otomatik oluşturulan örnek değişkenler kamusal görünürlüğünü verilmiştir.

Neden sadece kod yazmak ve kendiniz için görmek dont?

<?php
class Foo
{
    public function __construct()
    {
        $this->bar = 'baz';
    }
}

$foo = new Foo;
echo $foo->bar; // outputs 'baz'

ve

var_dump($foo);

verir

object(Foo)#1 (1) {
    ["bar"] => string(3) "baz"
}

ancak

$r = new ReflectionObject($foo);
$p = $r->getProperty('bar');
var_dump($p->isPublic());

, bilinmeyen varlık 'bar' ile ilgili bir özel durum atar iken

$r = new ReflectionObject($foo);
$p = $r->getProperties();
var_dump($p[0]->isPublic());

true dönecektir.

Now, should you do this type of assignment? Answer is no. This is not good OOP design. Remember, OOP is about encapsulation. So, if bar is describing some public property of the class, make it explicit ve declare it in your class as public $bar. If it is supposed to be private declare it as private $bar. Better yet, dont use public properties at all ve make them protected ve provide access to them only through getters ve setters. That will make the interface much more clearer ve cleaner as it conveys what interaction is supposed to be possible with an object instance.

Assigning properties on the fly here ve there across your code, will make maintaining your code a nightmare. Just imagine somewhere along the lifecylce of Foo someone does this:

$foo = new Foo;
$foo->monkey = 'ugh';

echo $foo->monkey; // outputs 'ugh'

Now, from looking at the class definition above, there is absolutely no way, a developer can see there is now a monkey patched into Foo. This will make debugging a pain, especially if code like this is frequent ve distriancaked across multiple files.

evet sen / beklediğiniz umut ediyorum gibi çalışır.

Bunu denedin mi?

Bu mümkün ama sıkı hatalar alabilirsiniz. Dinamik bu değişkenleri oluşturmak gerekiyorsa, muhtemelen yanlış bir şey yapıyorsun.

Ya bir fonksiyon içine değiştirmeniz gerekir:

function var($no) { .. }

veya __ get (http://ca.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members) kullanın

Ben size, örneğin, bu taklit php sihirli işlevleri kullanabilirsiniz anında özel değişkenleri yapmak istedim

MyClass

<?php
class MyClass {
    public $var1;
    public $var2;
    private $data = array();

    public function __get($key) {
        // for clarity you could throw an exception if isset($this->data[$key]) 
        // returns false as it is entirely possible for null to be a valid return value
        return isset($this->data[$key]) ? return $this->data[$key] : null;
    }

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

Main

<?php
$test = new MyClass();
$test->myVar = 'myVar is technically private, i suppose';
echo $this->myVar; // 'myVar is technically private
?>

Bu dinamik olarak oluşturulan değişkenler teknik özel olsa da, onlar i görüntü dinamik özel örnek değişkenleri oluşturmak isteyen için amaç olamaz ... infact kamuya erişilebilir. Ben tasarım soru.