我有多个使用静态方法的类.这些函数使用连接到数据库
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
Run Code Online (Sandbox Code Playgroud)
其中常量DB_SERVER,DB_USER,DB_PASS,DB_NAME是在全局可访问文件中定义的数据库变量.最近,我的网站开始变得缓慢,在分析脚本后,我意识到创建对象($ mysqli)的调用导致了这个问题.
我的大多数课程都是从mysqli扩展而来的
public function __construct($user_id) {
parent::__construct(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
$this->retrieve_user_details($user_id);
$this->check_user_account_type();
}
Run Code Online (Sandbox Code Playgroud)
据我所知,静态方法不要使用__construct方法.
有人可以指导我如何创建$ mysqli对象,以便所有需要它的静态方法都可以访问它.
在PHP中是否有一种方法可以使用在其声明中具有可选参数的函数,其中我不必传递已经声明了值的可选参数,并且只传递具有不同值的下一个参数.参数列表.
假设我有一个有4个参数的函数,2个强制,2个可选.我不想为可选参数使用空值.在使用中,有我想要使用的功能和值3的情况下RD说法是一样的默认值,但4的值个参数是不同的.
我正在寻找一个不那么详细的解决方案,它允许我只传递与默认值不同的参数而不考虑函数声明中的顺序.
createUrl($host, $path, $protocol='http', $port = 80) {
//doSomething
return $protocol.'://'.$host.':'.$port.'/'.$path;
}
Run Code Online (Sandbox Code Playgroud)
我发现自己重复声明变量,以便我可以使用函数即使用$ port,我使用函数作用域外的默认值重新声明$ protocol即
$protocol = "http";
$port = 8080;
Run Code Online (Sandbox Code Playgroud)
有没有办法传递第二个可选参数($ port)而不传递$ protocol,它会"自动"填写$ protocol的默认值ie
getHttpUrl($server, $path, $port);
Run Code Online (Sandbox Code Playgroud)
这在某些语言中是可能的,例如命名可选参数形式的Dart.请参阅此SO线程中的用法.他们是PHP中的类似解决方案
我何时应该调用mysqli :: close?我从来没有习惯使用if语句来检查bind_param(),prep()和execute()是否成功.我应该在方法的末尾(下面)调用$ stmt-> close().或者我应该在每个条件之后调用它,确保我关闭数据库连接,即使进程在某个阶段失败,例如绑定参数.
public function function_name($id,$new_id ){
$query = "UPDATE TABLE SET name = ? WHERE field = ? ";
if($stmt=$this->prepare($query)){
if($stmt->bind_param("is", $id, $new_id)){
if($stmt->execute()){
}else{//Could not execute the prepared statement
$message = "Could not execute the prepared statement";
}
}else{//Could not bind the parameters
$message = "Could not bind the parameters";
}
}else{
$message = "Could not prepare the statement";
}
return $message
}
Run Code Online (Sandbox Code Playgroud)