0

I'm new to defining classes so I hope this isn't a trivial question.

I want to end up with a collection of data in an object that I access through parameters such as:

AllData->A->Discount->Amount AllData->A->Discount->Percentage AllData->A->Claimed->Amount AllData->A->Claimed->Percentage 

I started with

class AllData { public $Discount; public $Claimed; } 

How do I defined the next levels (A, A->Amount, A->Percentage, etc.) of the object class?

3
  • you should elaborate whether all of the internal objects extends the same interface and have same properties Commented Dec 16, 2016 at 13:55
  • Is there a reason not to use an array? Commented Dec 16, 2016 at 14:17
  • An array would work in the simplest case as I've described it, but I'm trying to expand my understanding of classes and objects by using them. Commented Dec 16, 2016 at 17:58

1 Answer 1

2

You should check \stdClass out.

class AllData { public $Discount; public $Claimed; public function __construct() { $Discount = new \stdClass(); $Discount->Amount = 100; $Discount->Percentage = 300; } } 

Now you can access the Discount Amount like this:

$object = new AllData(); echo $object->Discount->Amount; 

This would be the fastest way as it seems you have classes that contain only attributes (so stdClass is fine for you).

Sign up to request clarification or add additional context in comments.

2 Comments

I don't know why it didn't occur to me to use stdClass within a class.
Octavian's response has me on the right track but how do I go to the next level? If I want $Discount->Amount->USA and $Discount->Amount->CDN how do I define those? When I tried adding $Discount->Amount = new stdClass(), I get: "Warning: Creating default object from empty value"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.