将数组作为数组元素分配给PHP';s类变量/属性


Assign Arrays as Array Elements to a PHP's Class Variable/Property

这是我的代码=>

class Dbhead{
public static $category=array(
"id"=>"Id",
"title"=>"Title",
"code"=>"Code",
"description"=>"Description",
"remarks"=>"Remarks"
);
public static $client=array(
"id"=>"Id",
"title"=>"Title",
"name"=>"Name",
"mobile"=>"Mobile",
"address"=>"Address",
"remarks"=>"Remarks"
);
    public $allfields=array(
        "client"=>self::$client,
        "category"=>self::$category
    );
}

分配$client&CCD_ 2数组到CCD_。我尝试过更改$client&$category仅公开。

我已经尝试了我知道的所有可能的方法来实现它,除了使用方法/函数,因为我不想这样。

你不能。手册上是这么说的。

作为一项工作,你可以这样做:

class Dbhead
{
    public static $category = [
        "id"          => "Id",
        "title"       => "Title",
        "code"        => "Code",
        "description" => "Description",
        "remarks"     => "Remarks",
    ];
    public static $client = [
        "id"      => "Id",
        "title"   => "Title",
        "name"    => "Name",
        "mobile"  => "Mobile",
        "address" => "Address",
        "remarks" => "Remarks",
    ];
    public static $allfields;
    // Arguably not the most elegant way to solve the problem
    // Since this is a setter without an argument
    public static function setClient()
    {
        static::$allfields['client'] = static::$client;
    }
    public static function setCategory()
    {
        static::$allfields['category'] = static::$category;
    }
}

或者非静态的东西。你可以把静态和非静态混合在一起,但嘿,没那么好。

class DbHead{
    protected $category, $client, $allFields;
    public function __construct(array $category,array $client)
    {
        $this->category = $category;
        $this->client = $client;
        $this->allFields['client'] = $client;
        $this->allFields['category'] = $category;
    }
    public function getCategory()
    {
        return $this->category;
    }
    public function getClient()
    {
        return $this->client;
    }
    public function getAllFields()
    {
        return $this->allFields;
    }
    // Alternatively provide setters for each field in particular
    // If you don't wish to initialize the values on class instantiation
    public function setCategory(array $category)
    {
        $this->category = $category;
        return $this;
    }
    public function setClient(array $client)
    {
        $this->client = $client;
        return $this;
    }
    public function createAllFields()
    {
        $this->allFields['client'] = $this->client;
        $this->allFields['category'] = $this->category;
    }
}
$dbHead = new DbHead([
    "id"          => "Id",
    "title"       => "Title",
    "code"        => "Code",
    "description" => "Description",
    "remarks"     => "Remarks",
], [
    "id"      => "Id",
    "title"   => "Title",
    "name"    => "Name",
    "mobile"  => "Mobile",
    "address" => "Address",
    "remarks" => "Remarks",
]);
$dbHead->createAllFields();