0

I am trying to create class properties for each element in an array. The array is already created at this point, I'm just creating it here for demonstration purposes.

I'm not too familiar with classes and objects. Could someone help me out?

class MyClass  
{  
 $days['first'] = "Mon";
 $days['second'] = "Tue";
 $days['third'] = "Wed";

 foreach ($days as $k => $v) {
     public $k = $v;
 }

}  

$obj = new MyClass;  

echo $obj->first; // Mon

I keep getting "Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION".

MultiDev
  • 9,449
  • 22
  • 69
  • 132
  • 2
    If you just want a value object, then `$obj = (object) $array;` would also work. – mario Jul 02 '12 at 22:33
  • This will cast it to an object of type stdClass. See http://stackoverflow.com/questions/931407/what-is-stdclass-in-php – Cameron Martin Jul 02 '12 at 22:34
  • The syntax error btw pertains to your ... invalid syntax. You need to preface each `$days["xx"]=` "assignment" with `var` or `public`. Whereas `public` is not a valid statement within the function. (Oh, wait, there isn't a function even). Please check http://www.php.net/manual/en/language.oop5.properties.php again. – mario Jul 02 '12 at 22:36

3 Answers3

1

That's not possible. However, you can create them in your constructor:

public function __construct() {
    $days = array();
    $days['first'] = "Mon";
    $days['second'] = "Tue";
    $days['third'] = "Wed";
    foreach($days as $k => $v)
        $this->$k = $v;
}

This will create public variables - so unless you want them private/protected that's the easiest way to achieve what you want.

Niko
  • 25,682
  • 7
  • 85
  • 108
ThiefMaster
  • 285,213
  • 77
  • 557
  • 610
1

Use a constructor to set the properties dynamically using $this->$key from an array that is passed in as a parameter, like so:

class MyClass  
{  
    function __construct( $dates) {
        foreach( $dates as $k => $v) 
            $this->$k = $v;
    }
}

// Can also put this into the __construct() function
$days = array();
$days['first'] = "Mon";
$days['second'] = "Tue";
$days['third'] = "Wed";

$obj = new MyClass( $days);
echo $obj->first;

$this->$k is a type of variable-variables where you can set the name of a variable using the value of another variable.

nickb
  • 56,839
  • 11
  • 91
  • 130
1

You can also utilize the magic __get() method for this task:

class MyClass {
    private $days = array('first' => 'Mon', ...);

    public function __get($key) {
        if (isset($this->days[$key])) {
            return $this->days[$key];
        }

        throw new Exception("Couldn't find a property for key $key");
    }
}
Niko
  • 25,682
  • 7
  • 85
  • 108