php - 如何使用 PHP7 从静态方法调用 trait 的非静态方法?
问题描述
trait ClearFolder
{
public function clearFolder($dir)
{
//codes...
}
public function clearInFolder($dir)
{
$this->clearFolder($dir);
mkdir($dir);
}
}
use boot\library\traits\ClearFolder;
class FileCache
{
//codes....
use ClearFolder;
public static function clearAll()
{
//Case1. Uncaught Error: Using $this when not in object...
$this->clearInFolder(self::$storage . '/');
//Case2. Non-static method boot\libr... should not be called statically
self::clearInFolder(self::$storage . '/');
//Case3. Cannot instantiate trait...
$trait = new ClearFolder;
}
}
要在静态方法中使用另一个类的非静态方法,我必须使用 new 关键字创建一个实例。但是我不能使用带有特征的“新”。
我使用'declare (strict_types = 1);' 和'error_reporting(E_ALL);'。
我应该静态更改特征的方法并替换使用该特征的所有内容吗?
解决方案
如果要使用 trait 中的非静态函数,则必须创建一个实例:
trait trait1
{
public function dummy()
{
var_dump("fkt dummy");
}
}
class c1{
use trait1;
public static function static1(){
(new static)->dummy();
}
}
c1::static1(); //string(9) "fkt dummy"
或者您将特征中的函数声明为静态:
trait trait1
{
public static function dummy()
{
var_dump("fkt dummy");
}
}
class c1{
use trait1;
}
c1::dummy(); //string(9) "fkt dummy"
不好,但有效。但是你不应该在不考虑你的代码设计的情况下使用它。
推荐阅读
- database - 无法在 SQL Server Management Studio 的 SQLite 数据库(.db 文件)中运行 JSON_VALUE
- python - 加载 Keras 模型并使用它进行预测
- excel - 使用 VBA 从 Excel 格式化电子邮件正文
- r - rbind.fill 基于通用模式 R
- outlook - 如何将 Azure Devops 日历集成到 Outlook
- c# - 使用 IIS 托管服务的问题 - 本地和远程
- python - Manjaro 上的旧版 Python (Arch Linux)
- regex - 我可以在单个正则表达式字符串中使用正则表达式提取值吗
- nebula-graph - 遇到错误:使用 Nebula Graph 数据库查询时获取邻居失败
- ios - 无法在 iOS 应用上使用 IPv6 从 RTMP HLS 服务器观看直播