phpedi

PHP creating an object using a variable to point to the correct class


Sorry not the best title. I am building an application with many different classes that will be called by a document builder class that takes an Array of what are defined as segments that are then used to reference the segments class to then be built into the document. I provided the Document class and the SegmentConfig file that references which segment points to which file location.

Reference Below First

I could not find a definitive answer on how I could use this to then generate the segment object could I do it like use $segmentObjectLocation as it would be equal to something like 'Edi\Segments\AmtSegment'. If anyone has some insight.

Other info: the reason I am trying to do it some way like this is becuase this will be used in multiple places though out the application.

$segmentLocation = include('SegmentConfig.php');
class Document{
    public function __construct($structure){
           $this -> documentStructure = $structure;
           foreach($structure as $segment){
                   buildSegment($segment);
          }
    }

    public function buildSegment($segment){
           $segmentObjectLocation = $segmentLocation ->{$segment};   
       }

} 
<?php
namespace Edi;

SegmentConfig.php

return (object) array(
       'AMT' => 'Edi\Segments\AmtSegment',
       'B4' => 'Edi\Segments\B4Segment',
       'BEG' => 'Edi\Segments\BegSegment',
       'CTT' => 'Edi\Segments\CttSegment',
       'DTM' => 'Edi\Segments\DtmSegment',
       'FOB' => 'Edi\Segments\FobSegment',
       'GE' => 'Edi\Segments\GeSegment',
       'GS' => 'Edi\Segments\GsSegment',
       'IEA' => 'Edi\Segments\IeaSegment',
       'ISA' => 'Edi\Segments\IsaSegment',
       'MSG' => 'Edi\Segments\MsgSegment',
       'N1' => 'Edi\Segments\N1Segment',
       'N2' => 'Edi\Segments\N2Segment',
       'N3' => 'Edi\Segments\N3Segment',
       'N4' => 'Edi\Segments\N4Segment',
       'N9' => 'Edi\Segments\N9Segment',
       'PER' => 'Edi\Segments\PerSegment',
       'PID' => 'Edi\Segments\PidSegment',
       'PO1' => 'Edi\Segments\Po1Segment',
       'Q2' => 'Edi\Segments\Q2Segment',
       'R4' => 'Edi\Segments\R4Segment',
       'REF' => 'Edi\Segments\RefSegment',
       'SAC' => 'Edi\Segments\SacSegment',
       'SE' => 'Edi\Segments\SeSegment',
       'ST' => 'Edi\Segments\StSegment',
       'TC2' => 'Edi\Segments\Tc2Segment',
       'TD1' => 'Edi\Segments\Td1Segment',
       'TD4' => 'Edi\Segments\Td4Segment',
       'TD5' => 'Edi\Segments\Td5Segment',
)


Solution

  • Not that this sounds like a particularly great idea, but:

    class Foo {}
    $n = 'Foo';
    $f = new $n();
    var_dump($f);
    

    Output:

    object(Foo)#1 (0) {
    }