首页 > 解决方案 > 如何获取公共类属性(不是继承的)

问题描述

有没有办法只获取 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"
    ]

有什么解决办法吗?

标签: phplaravel

解决方案


显示的属性不是继承的,它们是从 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$pastedtrait显示T,但不是$foo从 class显示A

同样,您的输出不是显示来自类的字段,Mailable而是来自语句导入的两个特征use Queueable, SerializesModels;

这是按设计行事的:特征被认为是“编译时复制和粘贴”,因此特征中包含的成员与直接在类中定义的成员没有区别。


推荐阅读