分配数组作为数组元素的PHP的类变量/属性
这是我的代码=>分配数组作为数组元素的PHP的类变量/属性
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
& $category
阵列$allfields
作为元素中断的代码。 我已尝试将$client
& $category
更改为仅公开。
我已经尝试了所有可能的方法,我知道要实现它,除了使用方法/函数,因为我不想这样做。
你不能。 manual says so。
作为一种变通,你可以这样做:
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();
但是,当我以程序方式或非OOP方式(即,没有Class)执行此操作时,此工作正常。 –
当然,它在非OOP中工作得很好,它只是分配内容。但是如果你想在课堂上学习,你必须以正确的方式来完成。 –
@andrew与__construct()不同,我需要触发setClient()和setCategory()吗? –
在你的'__construct()'方法中做。 –
从[PHP文档](http://www.php.net/manual/en/language.oop5.properties.php)这个声明可能包含一个初始化,但是这个初始化必须是一个常量值 - 即,它必须能够在编译时进行评估,并且不得依赖运行时信息进行评估。“......即,你不能......你必须定义一些像这样动态的东西在方法 –
@Julien我不想使用任何方法。我在寻找替代品。 '__construct()'是一个魔术棒。我正在尝试,因为它是从过程到面向对象的过渡时间。 –