Dynamically add a private property to an object

后端 未结 4 1462
感动是毒
感动是毒 2020-12-11 19:40

I have a class:

class Foo {
    // Accept an assoc array and appends its indexes to the object as property
    public function extend($values){
        forea         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-11 19:51

    I would work with the whole array:

    $Foo = new Foo;
    $Foo->setOptions(array('name' => 'Bee'));
    
    class Foo {
        private $options = array();
    
        public function setOptions(array $options) {
            $this->options = $options;
        }
    
        public function getOption($value = false) {
            if($value) {
                return $this->options[$value];    
            } else {
                return $this->options;
            }
        }
    }
    

    Then you have more options when you need other values and you can iterate through the array and work with them. When you have single variable in most cases its a bit complecated.

提交回复
热议问题