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 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办