php - 如何获取公共类属性(不是继承的)
问题描述
有没有办法只获取 Mailable 类中的公共类属性(不是继承的),例如:
<?php
namespace App\Mail;
use App\Mail\Mailable;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class TestMail1 extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
public $name; // i want to get only this
public $body; // and this
/**
* Create a new message instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.simpleview')->subject('New Mail');
}
}
此类(TestMail1)从扩展类(Mailable)继承了许多属性,但我只想获取在类本身中定义的name
和属性body
我试试这个:
$mailable = (new mailable1);
$data = new ReflectionClass($mailable);
$properties = $data->getProperties(ReflectionProperty::IS_PUBLIC);
$properties_in = [];
foreach ($properties as $prop) {
if ($prop->class == $data->getName())
$properties_in[] = $prop->name;
}
dd($properties_in);
但这会返回:
array:8 [▼
0 => "name"
1 => "body"
2 => "connection"
3 => "queue"
4 => "chainConnection"
5 => "chainQueue"
6 => "delay"
7 => "chained"
]
有什么解决办法吗?
解决方案
显示的属性不是继承的,它们是从 Trait 中包含的。
如果您看一个更简单的示例,您可以看到差异:
trait T {
public $pasted;
}
class A {
public $foo;
}
class B extends A {
use T;
public $bar;
}
$data = new ReflectionClass(B::class);
$properties = $data->getProperties(ReflectionProperty::IS_PUBLIC);
$properties_in = [];
foreach ($properties as $prop) {
if ($prop->class == $data->getName()) {
$properties_in[] = $prop->name;
}
}
print_r($properties_in);
这$bar
从 classB
和$pasted
trait显示T
,但不是$foo
从 class显示A
。
同样,您的输出不是显示来自类的字段,Mailable
而是来自语句导入的两个特征use Queueable, SerializesModels;
这是按设计行事的:特征被认为是“编译时复制和粘贴”,因此特征中包含的成员与直接在类中定义的成员没有区别。
推荐阅读
- c# - 多个网站的通用配置部分
- laravel - Laravel:如何从具有关系的 3 个表中获取数据
- javascript - 如何只关闭打开的 mdDialogs 之一?AngularJs
- ubuntu - 证书续订后,CouchDB 无法通过 https 工作
- c# - 导航后部分 UWP 页面不刷新
- php - Google Analytics API 返回不可访问的数组
- node.js - 使用 Bull.js 通过在重复规则中提供时间来安排可重复的作业
- gradle - 如有必要,在自动部署时更新 gradle 版本
- javascript - 如何使用打字稿定义文件中的枚举?
- apache-spark - 激发有效分布配对以比较群组