PHP 扩展类属性
我在 PHP 应用程序中有两个类,例如 B 扩展了 A。 A 类有一个函数,它以 SQL 插入查询数组的形式返回它的一些其他属性,例如,
Class A {
$property_a;
$property_b;
$property_c;
$property_d;
function queries() {
$queries = array();
$queries[] = "INSERT INTO xxx VALUES " . $this->property_a . ", " . $this->property_b";
$queries[] = "INSERT INTO yyy VALUES " . $this->property_b . ", " . $this->property_d";
}
}
我希望 B 类有一个类似(相同)的函数,它对 B 类的属性执行相同的操作,同时仍然保持来自 A 类的值。这个想法是每个查询都将同时通过最终函数,即:
$mysqli->query("START TRANSACTION");
foreach($queries as $query) {
if(!$mysqli($query)) {
$mysqli->rollback();
}
}
IF all OK $mysqli->commit();
实现这一目标的最简单方法是什么? 任何建议和想法都表示赞赏。 谢谢!
I have two classes in a PHP application, B extending A for example.
Class A has a function which returns some of its other properties in the form of an array of SQL insert queries eg
Class A {
$property_a;
$property_b;
$property_c;
$property_d;
function queries() {
$queries = array();
$queries[] = "INSERT INTO xxx VALUES " . $this->property_a . ", " . $this->property_b";
$queries[] = "INSERT INTO yyy VALUES " . $this->property_b . ", " . $this->property_d";
}
}
I would like class B to have a similar (identical) function which does the same thing for class B's properties, whilst still maintaining the values from class A. The idea being that each query will be passed through a final function all at the same time ie:
$mysqli->query("START TRANSACTION");
foreach($queries as $query) {
if(!$mysqli($query)) {
$mysqli->rollback();
}
}
IF all OK $mysqli->commit();
What would be the simplest way to achieve this?
Any advice and ideas appreicated.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 B::queries() 中,您可以调用 parent 的实现该方法并将数据附加到 a::queries() 返回的数组中。
但是您可能(也)想研究一个 ORM 库,例如 doctrine。
Within B::queries() you can call the parent's implementation of that method and append your data to the array a::queries() returns.
But you might (also) want to look into an ORM library like e.g. doctrine.
使用 getter 函数来获取 requests() 中的属性。在每个类中,您可以控制查询函数使用的值。
Use a getter function to grab the properties in queries(). In each class you can then control what values the queries function is using.
如果不使用另一个实例的信息初始化较新的类,您就无法真正将内容从一个实例转移到另一个实例。所以你可以扩展A来改变B的查询函数内容,然后用A实例初始化B:
如果A和B 100%相同(包括查询函数),则克隆A:
$a = 新 A();
$b = 克隆 $a;
You can't really carry over stuff from one instance to another without initializing the newer class with the other instance's information. So you can extend A to change B's query function contents, then initialize B with an A instance:
If A and B are 100% the same (including query function), just clone A:
$a = new A();
$b = clone $a;
那么你想使用A类和B类中的属性吗?
你可以通过使用parent来做到这一点。
B类:
so you want to use the properties in class A and class B?
you can do this by using parent.
in class B: