基于数组值动态分配属性名称

时间:2018-03-29 20:07:43

标签: php arrays oop object properties

我正在尝试创建一个根据用户输入生成动态类属性的类 将有一个根据用户输入数据创建的数组。这个数组应该作为一个例子:

$array = array(
    # The boolean values are not relevant in this example
    # The keys are important

    'apple' => true,
    'orange' => false,
    'pear' => false,
    'banana' => true,
);

现在我想用数组键作为类属性创建一个新类:

class Fruit {
    public $apple;
    public $orange;
    public $pear;
    public $banana;

(etc.)
}

我现在必须手动记下所有四个属性 有没有办法让它自动化?

2 个答案:

答案 0 :(得分:0)

<?php

class MyClass 
{
    public function __construct ($config = []) 
    {
        foreach ($config as $key => $value) {
            $this->{$key} = $value;
        }
    }
}

$myClass = new MyClass(['apple' => 1, 'orange' => 2]);

echo $myClass->apple;
?>

这应该可以帮到你

答案 1 :(得分:0)

你走了,

我在那里放了一些额外的东西:

class MyClass implements Countable, IteratorAggregate
{
    protected $data = [];

    public function __construct (array $data = []) 
    {
        foreach ($data as $key => $value) {
            $this->{$key} = $value;
        }
    }

    public function __set($key, $value){
        $this->data[$key] = $value;
    }

    public function __get($key)
    {
        if(!isset($this->{$key})) return null; //you could also throw an exception here.
        return $this->data[$key];
    }

    public function __isset($key){
        return isset($this->data[$key]);
    }

    public function __unset($key){
        unset($this->data[$key]);
    }

    public function __call($method, $args){

        $mode = substr($method, 0, 3);
        $property = strtolower(substr($method, 3)); //only lowercase properties
        if(isset($this->{$property})) {
            if($mode == 'set'){
                $this->{$property} = $args[0];
                return null;
            }else if($mode == 'get'){
                return $this->{$property};
            }
        }else{
            return null; //or throw an exception/remove this return
        }
        throw new Exception('Call to undefined method '.__CLASS__.'::'.$method);
    }

    //implement Countable
    public function count(){
        return count($this->data);
    }

    //implementIteratorAggregate
    public function getIterator() {
        return new ArrayIterator($this->data);
    }

}

测试它:

$myClass = new MyClass(['one' => 1, 'two' => 2]);

echo $myClass->two."\n";

//Countable
echo count($myClass)."\n";

//dynamic set
$myClass->three = 3;

echo count($myClass)."\n";

//dynamic get/set methods. I like camel case methods, and lowercase properties. If you don't like that then you can change it.
$myClass->setThree(4);
echo $myClass->getThree()."\n";

//IteratorAggregate
foreach($myClass as $key=>$value){
    echo $key.' => '.$value."\n";
}

输出

2 //value of 2
2 //count of $data
3 //count of $data after adding item
4 //value of 3 after changing it with setThree
//foreach output
one => 1
two => 2
three => 4

Test it online

Disclamer

一般来说,手动定义类更好,这就像IDE的工作方式。您可能也会遇到问题,因为您不一定会提前知道课程中定义的内容。您没有具体的类定义。

几乎所有以__开头的方法(至少在我的代码中)都是一种PHP魔术方法(是的,这是一件事)。当我第一次学会如何使用这些时,我认为它非常酷,但现在我几乎从不使用它们......

现在,如果你想创建一个包含该代码的实际.php文件,那就是另一个对话。 (如果您想要功能或实际文件,则不是100%清晰)

干杯。