I recently realized my currently approach on a project would greatly improve with the use of better/more descriptive objects. As such, I realized that I want an array of objects to be a member of another class.
Edit: I wasn't clear as to what my question was. My question is thus: How do I have an array in class LogFile that contains objects of type Match?
class LogFile
{
public $formattedMatches;
public $pathToLog;
public $matchCount;
** An array called matches that is an array of objects of type Match **
}
class Match
{
public $owner;
public $fileLocation;
public $matchType;
}
Eventually I want to be able to do something like:
$logFile = new LogFile();
$match = new Match();
$logFile->matches[$i]->owner = “Brian”;
How do I do what I described? In other words, what do I need to do in class LogFile
to create an array that contains objects of type Match
?
Just include
Then when you want to add to the the array:
Just create another public variable for matches. Then, you can initialize it as an array in the constructor method.
Yeah, that would work.
You could use an object of
SplObjectStorage
as this is intended to store objects.PHP isn't strongly typed - you can put whatever you like in any variable. To add to matches, just do
$logFile->matches[] = new Match();
.This is an addition to the answer by Brad or by swatkins. You wrote:
You can create an "array" that only can contain
Match
objects. This is fairly easy by extending fromArrayObject
and only accepting object of a specific class:You then make you class
LogFile
use thatMatches
class:In the constructor you set it up, the new
Matches
"Array". Usage:Demo - Hope this is helpful.