什么是在php中的抽象类中使用构造函数 [英] What is the use of constructor in abstract class in php

查看:210
本文介绍了什么是在php中的抽象类中使用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在提出问题之前就跟着这个链接 - 答案在JAVA上下文,这适用于构造函数在PHP

I followed this link already before asking - Answer is in JAVA context and this for constructor in PHP .

由于我是初学者,我的实现我的PHP代码在OOP的概念,所以我真的愿意知道的用法和好处或者何时在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.

请在现实世界环境中提供一个示例来更好地抓住这个概念。

Please provide an example in real world context to grab the concept better.

PS - 虽然我遵循 PHP手册来了解OOP概念,但我发现它有点难以理解,任何关于链接/博客的帮助是非常感激的。

PS - Although I am following PHP Manuals to understand OOP concepts but I am finding it little bit hard to understand, any help with the links/blog to follow is really appreciable.

我的代码 -

<?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(); 


推荐答案

抽象类中的构造方法与具体类。例如,如果您需要初始化一些数据或分配一些资源,请使用构造函数。

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.

我给你一个例子:

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'));

这篇关于什么是在php中的抽象类中使用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆