繁体   English   中英

PHP类中的对象数组

[英]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类型对象的数组吗?

这是Bradswatkins答案 的补充 你写了:

我需要在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM