anders
anders

Reputation: 1545

Store values in PHP

I have an object that has a single comment on it and then that object has subobjects that each can have a comment on it. As it is today I have a single variable to store the comment on the whole object and a list to store the comments for the objects subobjects.

public $TestResultComments = array();
public $Comment;

Now I not only want to store the plain text of a comment but also store the username of that person that has wrote it and the timestamp. So instead of the single variable $Comment I now want to store three. What is the best way to store this, into an array or is there something similar as in Haskell where there are Tuples?

$comment = odbc_result($result, "comment");
$userName = odbc_result($result, "username");
$timeStamp = odbc_result($result, "timestamp");
$testResult->Comment = $comment;//This is what I do today, but I also want to include $userName and timestamp here

The second part is where I store the comments for the subobjects.

for ($i = 1; $i <= $no_results; $i++) {
    odbc_fetch_row($result, $i);
    $type = trim(odbc_result($result, "result"));
    $testResult->TestResultComments[$type] = trim(odbc_result($result, "comment"));//Here I aswell want to store "comment","username" and "timestamp" as they are called in the database table and not only "comment" as I currently do.
}

As you can see in the second example I have a keyvalue "result" to get the comment. Here I also want to get the values ("comment","username","timestamp") instead of a single value as today.

Thanks in advance.

Upvotes: 1

Views: 53

Answers (1)

christopher
christopher

Reputation: 27346

Seems like a nice situation to use the stdClass. stdClass allows you to dynamically declare fields for an object. You have an array of these, with say result as the key.

Example

$allValues = array();

// Create the values.
$values = new stdClass();
$values->comment = $comment;
$values->username = $username;
$values->timestamp = $timestamp;

$allValues[$result] = $values;

This gives you a direct mapping from a $result to several values, in a clean and OOP way. In the future, assuming you've created $result, you can say..

$values = $allValues[$result];

echo "The username is ". $values->username;

I really like using it because it makes your code super clean and OOP in syntax. For loosely typed languages like PHP, readability can sometimes be lost so it's important you maintain practises like this to keep things easy to understand.

Upvotes: 2

Related Questions