doudu2591 2015-05-23 00:43
浏览 71
已采纳

在php中调用一个从子类到父类的函数[关闭]

please check these classess:

class DB
{   
    protected saveINDB($name)
    {
       //insert $name to DB
    }

}

class Items extends DB
{
    private $name;

    function __construct($name) 
    {
          $this->name = $name;        
    }        
}

I want save $name in 'Item' to database via a method in 'DB' class.

I think I can do it like this:

$item = new Item('Free');
$item->saveINDB($item->name);

is it right?

No how can I call function automaticly in second class?

for example...when I create 'Item' object. it call saveINDB() in 'DB' class in save $name in database.(like propertise in __construct() method)

something like this:

class Items extends DB
{
    private $name;

    function __construct($name) 
    {
          $this->saveINDB($name);        
    }        
}

I hope you underestand me.

  • 写回答

2条回答 默认 最新

  • dongtao4787 2015-05-23 00:59
    关注

    $this->saveINDB($name); will work fine in the constructor, as per your example. There's no need to use parent:: unless you're overriding the method, because the whole point of extending a class is that the child inherits all the methods of the parent.

    There is an error in your DB class though, which might be causing you issues:

    protected function saveINDB($name) // function was missing

    Here's a working demo on codepad

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?