在PHP类中动态创建实例变量 [英] Dynamically creating instance variables in PHP classes
问题描述
我不确定这是否是一个简单的问题,但在PHP类中:
I'm not sure if this is a trivial questions but in a PHP class:
MyClass:
$ b
MyClass:
class MyClass {
public $var1;
public $var2;
constructor() { ... }
public method1 () {
// Dynamically create an instance variable
$this->var3 = "test"; // Public....?
}
}
主要:
$test = new MyClass();
$test->method1();
echo $test->var3; // Would return "test"
我将如何让这工作? Ps。我写了这么快,所以请忽略我在设置类或调用方法时出现的任何错误。
Does this work?? How would I get this to work? Ps. I wrote this quickly so please disregard any errors I made with setting up the class or calling methods!
EDIT
这些实例变量,我创建私人??
EDIT What about making these instance variables that I create private??
编辑2
感谢所有回应 - 每个人都是正确的 - 我应该自己测试了,但我第二天早上有一个考试,在学习时有这个想法,我想检查它是否工作。人们不断地暗示其糟糕的OOP - 也许,但它允许一些优雅的代码。让我解释一下,看看你还是这样认为。这是我想出的:
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...
}
只是把它放在一个关联数组,但我不能正确地命名该数组有意义的(即$ user-> data ['name'] ...丑陋。)无论哪种方式,你必须知道什么是数据库,所以我真的不明白什么是参数是它的混乱,特别是因为你可以只是var dump对象进行调试。
I could have just put it in an associative array but I can never correctly name that array something meaningful (ie. $user->data['name'] ... ugly.) Either way you have to know what is in the database so I do not really understand what the argument is that its confusing, especially since you can just var dump objects for debugging.
推荐答案
会真的工作。自动创建的实例变量具有公开的可见性。
Yes that will indeed work. Auto-created instance variables are given public visibility.
这篇关于在PHP类中动态创建实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!