gpt4 book ai didi

php - 为什么不调用父构造函数?

转载 作者:可可西里 更新时间:2023-11-01 00:11:00 25 4
gpt4 key购买 nike

我将 parent::__construct(); 添加到表和书签的构造函数中,以便让这段代码正常工作。为什么不自动调用它们?

如果我创建一个书签类型的对象 $obj_ref_bo = new bookmark(); 不应该书签也从它的每个父类(除了抽象类)创建对象。

调用链是

bookmark->table->database(abstract)->single_connect

    /*single_connect*/

class single_connect
{
protected static $_db_pointer = NULL;
private function __construct()
{
$this->_db_pointer = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_DATABASE);
}
public static function get_connection()
{
if(self::$_db_pointer == NULL)
{
return new self();
}
else
{
echo "Error:only one connection";
}
}
}

/*database*/

abstract class database
{
protected function __construct()
{
single_connect::get_connection();
}
static protected function query($query)
{
$result = mysql_query($query) or die(mysql_error());
return $result;
}
}

/*table*/

class table extends database
{
public $_protected_arr=array();
protected function __construct()
{
parent::__construct();
$this->protect();
}
protected function protect()
{
foreach($_POST as $key => $value)
{
$this->_protected_arr[$key] = mysql_real_escape_string($value);
}
}
}

/*bookmark*/

class bookmark extends table
{
function __construct()
{
parent::__construct();
$this->start();
}
function start()
{
if(this->test())
{
this->insert();
}
else
{
return 1;
}
}
function test()
{
if(this->test_empty())
{
return 1;
}
else
{
return 0;
}
}
function test_empty()
{
if(text::test_empty($this->_protected_arr))
{
return 1;
}
else
{
return 0;
}
}
function insert()
{
$url = $this->_protected_arr['url'];
$title = $this->_protected_arr['title'];
$email = $_SESSION['email'];
database::query("INSERT INTO bo VALUES ('$title', '$url', '$email')");
}
}

最佳答案

should not bookmark also create objects from each of its parent classes

这完全是您的选择,语言中没有要求调用父方法。

正如 PHP 手册简洁地指出的那样:

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

http://php.net/oop5.decon

关于php - 为什么不调用父构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6220848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com