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...?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked great. Thank you! I can understand how this works looking at this example. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.