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…?
The correct way would be:
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.