2

I have a string that I'm trying to use to create a class. I am trying to name each property and define its value based on the contents of the string. For example:

$mystring = "first_name=jane,last_name=doe";

$pieces = explode(",", $mystring);

foreach( $pieces as $key => $value){
    $eachvalue = explode("=",$value);

    class MyClass {  

        public $eachvalue['0'] = $eachvalue['1'];  

    }  

} // end foreach

$obj = new MyClass;

echo $obj->first_name; // Should echo "Jane"

I'm pretty new PHP classes, and this isn't working. I don't know if I'm close, or if I'm way off...?

MultiDev
  • 10,389
  • 24
  • 81
  • 148

1 Answers1

5

The correct way would be:

// Class definition
class MyClass {  

    public $first_name;
    public $last_name;

}

$mystring = "first_name=jane,last_name=doe";

// Instantiate the class
$obj = new MyClass;

// Assign values to the object properties
$pieces = explode(",", $mystring);
foreach ($pieces as $key => $value) {
  // this allows you to assign the properties dynamically
  list($name, $val) = explode("=", $value);
  $obj->$name = $val;
} // end foreach

echo $obj->first_name; // Should echo "Jane"

A class can only be defined once - by putting it in the loop, you are declaring it on every iteration of the loop. Also, a class would not hold the values that you want in an instance of an object, it is a skeleton that describes how an object will be. So what you do is define the class, instantiate it, and then assign values to it.

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
  • That worked great. Thank you! I can understand how this works looking at this example. Thanks again. – MultiDev Apr 12 '12 at 16:48