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