PHP - 另一个对象拥有的不确定数字对象

时间:2017-02-02 03:49:22

标签: php oop object

我有一个Project类/对象需要拥有(拥有)不确定数量的Phase对象。我不知道项目对象创建时的阶段数,所以我不想将Phase对象创建放在Project的构造函数中。

我的课程:

class Project {
     //some properties
}

class Phase {
     public $property;
}

我想这样做:

 $foo = $myProject->phase01->property;
 $bar = $myProject->phase06->property;
 //etc...

请知道如何最好地完成这项工作。

2 个答案:

答案 0 :(得分:1)

我不会使用动态属性。

如果阶段是一个集合,会将它们视为一个集合,以后可能会派上用场。 E.g.

class Project {

    private $phases = [];

     public function __get($property)
     {
        // if begins with "phase" and some number
        if ( preg_match("/^phase(\d+)$/", $property, $matches) ) {
            // if is set already, we return it
            if ( isset($this->phases[$matches[1]]) ) {
                return $this->phases[$matches[1]];
            }
            // if it isn't, it isn't :)
            return null;    
        }
     }

    public function __set($property, $value)
    {
        if ( preg_match("/^phase(\d+)$/", $property, $matches) ) {
            $this->phases[$matches[1]] = $value;
        }
    }

    public function addPhase(Phase $phase, $phase_number = null)
    { 
        if ($phase_number !== null) {
            $this->phases[$phase_number] = $phase;
        }
        else {
            $this->phases[] = $phase;
        }

        return $this;
    }

    public function getPhases()
    {
         return $this->phases;
    }

    // etc
}

class Phase {
  public $property = "";
  public function __construct($property) {
    $this->property = $property;
  }
}

$myProject = new Project();

$myProject->phase1 = new Phase('startup');

$myProject
      ->addPhase(new Phase('build'))
      ->addPhase(new Phase('cleanup'));

foreach ($myProject->getPhases() as $key => $phase) {
     echo "Phase $key: {$phase->property}", "\n";
}

答案 1 :(得分:0)

您可以实施php's magic methods之一,特别是__get

<?php

class Project {
     //some properties
     public function __get($property)
     {
        // if begins with "phase" and some number
        if ( preg_match("/^phase\d+$/", $property) === 1 ) {
            if ( !isset($this->$property) ) {
                $this->$property = new Phase;
            }

            return $this->$property;
        }
     }
}

class Phase {
     public $property;
}


$myProject = new Project;

//And I'd like to do this:

 $foo = $myProject->phase01->property;
 $bar = $myProject->phase06->property;
 //etc...