php - 不在 PHP 的对象上下文中使用 $this 时出错
问题描述
在尝试使用 Trait 从传入的字段构建类属性和字段时,我遇到了以下错误“未捕获的错误:不在对象上下文中使用 $this”。
我的方法:
public function createNewPet(array $petData): bool {
return self::save($petData);
}
我的方法是调用save()
方法:
/**
* @param array|null $fields
* @return bool|null
* @throws \ReflectionException
*/
public function save(?array $fields = null): ?bool
{
$values = [];
if (isset($fields)) {
foreach (Helper::getNonStaticProperties(static::class, false) as $prop) {
if (!property_exists(static::class, $prop)) {
continue;
}
$values[$prop] = $this->{$prop};
}
} else {
if (!is_array($fields)) {
$fields = [$fields];
}
foreach ($fields as $field) {
if (property_exists(static::class, $field)) {
$values[$field] = $this->{$field};
}
}
}
}
您可以看到此方法引用了以下辅助方法getNonStaticProperties()
:
/**
* @param string $object
* @param bool $includeParentProperties
* @param bool $includeTraitProperties
* @return array
* @throws \ReflectionException
*/
public static function getNonStaticProperties(
string $object,
bool $includeParentProperties = true,
bool $includeTraitProperties = false
) :array
{
if (!class_exists($object)) {
return []; //If $object is not a valid class, return empty array
}
//Create a reflection of the passed object
$reflection = new \ReflectionClass($object);
$static = $reflection->getStaticProperties(); //Get the reflections static properties
$allArr = $reflection->getProperties(); //Get the reflections properties
$all = null;
$static = array_keys($static);
foreach ($allArr as $prop) {
$all[] = trim($prop->name);
}
if (!is_array($all)) {
$all = [$all];
}
if (!is_array($static) || empty($static)) { //If $static is empty, simply return $all
$result = $all;
} else { // Return the list of variables that are present in $all but not present in $static
$result = array_diff($all, $static);
}
if (!$includeParentProperties && $parent = get_parent_class($object)) {
$parentProps = self::getNonStaticProperties($parent, true);
$result = array_diff($result, $parentProps);
}
if ($includeTraitProperties && !empty($traits = $reflection->getTraits())) {
$traitProps = [];
foreach ($traits as $trait) {
$traitProperties = $trait->getProperties();
foreach ($traitProperties as $prop) {
$traitProps[] = trim($prop->getName());
}
}
$result = array_diff($result, $traitProps);
}
return $result;
}
更新:将方法(显示在评论中)添加到问题中。
解决方案
public function createNewPet(array $petData): bool {
return self::save($petData);
}
您正在静态调用save
非静态方法。替换self::save
为$this->save
应该修复它。
推荐阅读
- docker - 在离线 Centos 服务器上安装 docker
- systemd - systemd:延迟发送 SIGTERM 两次,*然后*发送 SIGKILL?
- reactjs - 更新上下文时避免运行效果挂钩
- android - 无法解析配置“:app:debugRuntimeClasspath”的所有文件。对于谷歌广告
- pytorch - pytorch 中的一种热编码
- scanf - 为什么 scanf 在代码块 IDE 中无法正常工作
- python - 值错误。视图“users.views.register”没有返回 HttpResponse 对象。它返回 None 而不是
- python - 如何自动为帖子添加标签
- python - 使用 pandas 从 csv 的每一行中的行值中删除后缀
- python - 如何在嵌入中显示用户标签和头像?