[英]Array of objects within class in PHP
我最近意識到,通過使用更好/更具描述性的對象,我目前在項目上的方法將大大改善。 這樣,我意識到我希望對象數組成為另一個類的成員。
編輯:我不清楚我的問題是什么。 因此,我的問題是:如何在類LogFile中有一個包含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;
}
最終,我希望能夠執行以下操作:
$logFile = new LogFile();
$match = new Match();
$logFile->matches[$i]->owner = “Brian”;
我該怎么做? 換句話說,我需要在LogFile
類中創建包含Match
類型對象的數組嗎?
我需要在LogFile類中做什么以創建包含Match類型對象的數組?
您可以創建一個只能包含Match
對象的“數組”。 通過從ArrayObject
擴展並僅接受特定類的對象,這相當容易:
class Matches extends ArrayObject
{
public function offsetSet($name, $value)
{
if (!is_object($value) || !($value instanceof Match))
{
throw new InvalidArgumentException(sprintf('Only objects of Match allowed.'));
}
parent::offsetSet($name, $value);
}
}
然后,使您的LogFile
類使用Matches
類:
class LogFile
{
public $formattedMatches;
public $pathToLog;
public $matchCount;
public $matches;
public function __construct()
{
$this->matches = new Matches();
}
}
在構造函數中,您將其設置為新的Matches
“ Array”。 用法:
$l = new LogFile();
$l->matches[] = new Match(); // works fine
try
{
$l->matches[] = 'test'; // throws exception as that is a string not a Match
} catch(Exception $e) {
echo 'There was an error: ', $e->getMessage();
}
演示 -希望這會有所幫助。
只需為匹配創建另一個公共變量。 然后,可以在構造方法中將其初始化為數組。
class LogFile
{
public $formattedMatches;
public $pathToLog;
public $matchCount;
public $matches;
function __construct() {
$matches=array();
//Load $matches with whatever here
}
}
class LogFile
{
public $formattedMatches;
public $pathToLog;
public $matchCount;
public $matches = array();
}
PHP的類型不是很嚴格-您可以在變量中添加任何內容。 要添加到匹配項中,只需執行$logFile->matches[] = new Match();
。
是的,那行得通。
class LogFile
{
public $formattedMatches;
public $pathToLog;
public $matchCount;
public $matches = array();
}
class Match
{
public $owner;
public $fileLocation;
public $matchType;
}
$l = new LogFile();
$l->matches[0] = new Match();
只包括
public $matches = array();
然后,當您想添加到數組中時:
$matches[] = $match; // $match being object of type match
您可以使用SplObjectStorage
對象,因為它旨在存儲對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.