gpt4 book ai didi

php - 从 PHP 中的构造函数调用另一个构造函数

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

我想要一些在 PHP 类中定义的构造函数。但是,我的构造函数代码目前非常相似。如果可能的话,我宁愿不重复代码。有没有办法从 php 类的一个构造函数中调用其他构造函数?有没有办法在一个 PHP 类中有多个构造函数?

function __construct($service, $action)
{
if(empty($service) || empty($action))
{
throw new Exception("Both service and action must have a value");
}
$this->$mService = $service;
$this->$mAction = $action;

$this->$mHasSecurity = false;
}
function __construct($service, $action, $security)
{
__construct($service, $action); // This is what I want to be able to do, so I don't have to repeat code

if(!empty($security))
{
$this->$mHasSecurity = true;
$this->$mSecurity = $security;
}
}

我知道我可以通过创建一些 Init 方法来解决这个问题。但是有办法解决这个问题吗?

最佳答案

您不能像在 PHP 中那样重载函数。如果你这样做:

class A {
public function __construct() { }
public function __construct($a, $b) { }
}

您的代码将不会编译并出现您无法重新声明 __construct() 的错误。

这样做的方法是使用可选参数。

function __construct($service, $action, $security = '') {
if (empty($service) || empty($action)) {
throw new Exception("Both service and action must have a value");
}
$this->$mService = $service;
$this->$mAction = $action;
$this->$mHasSecurity = false;
if (!empty($security)) {
$this->$mHasSecurity = true;
$this->$mSecurity = $security;
}
}

关于php - 从 PHP 中的构造函数调用另一个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1712161/

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