php php抽象类中的构造函数有什么用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14272598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the use of constructor in abstract class in php
提问by swapnesh
I followed this link already before asking - Answer is in JAVA contextand this for constructor in PHP.
在询问之前我已经点击了这个链接 -答案是在 JAVA 上下文中,而 this 是在 PHP 中的构造函数。
Since I am starter, my implementation of my PHP code in OOP concepts, so I am really willing to know about the usage and benefits or when to use constructor in PHP abstract class.
由于我是初学者,我在 OOP 概念中实现了我的 PHP 代码,所以我真的很想知道 PHP 抽象类中的用法和好处或何时使用构造函数。
Please provide an example in real world context to grab the concept better.
请在现实世界中提供一个示例,以更好地掌握概念。
PS - Although I am following PHP Manualsto understand OOP concepts but I am finding it little bit hard to understand, any help with the links/blog to follow is really appreciable.
PS - 虽然我正在遵循PHP 手册来理解 OOP 概念,但我发现它有点难以理解,任何关于链接/博客的帮助都是非常值得赞赏的。
My Code -
我的代码 -
<?php
abstract class grandClass
{
abstract function grandmethod();
function __construct()
{
echo "I am grandClass constructor";
}
}
abstract class parentClass extends grandClass
{
abstract function raiseFlag();
function grandmethod()
{
echo "This is grandmethod!!!","<br />";
}
public function getValue()
{
echo "Zero is the blackhole for the numbers!!","<br />";
}
}
class childClass extends parentClass
{
function raiseFlag()
{
echo "Peaceful thoughts!!","<br />";
}
}
$myobj = new childClass();
$myobj->raiseFlag();
$myobj->getValue();
$myobj->grandmethod();
回答by Lauris
Constructor in abstract class is the same as in concrete class. Use constructors when they are needed, for example, if you need to intialize some data or assign some resources.
抽象类中的构造函数与具体类中的构造函数相同。在需要时使用构造函数,例如,如果您需要初始化某些数据或分配某些资源。
I'll give you an example:
我给你举个例子:
abstract class Db
{
protected $pdo;
public function __construct($pdo)
{
$this->pdo = $pdo;
}
abstract function select($table, $fields);
}
class Db_Mysql extends Db
{
public function select($table, $fields)
{
// Build MySQL specific select query
// then execute it with $this->pdo
}
}
class Db_Pgsql extends Db
{
public function select($table, $fields)
{
// Build PostgreSQL specific select query
// then execute it with $this->pdo
}
}
// Usage:
$db = new Db_Mysql($pdo);
$db->select('users', array('id', 'name'));

