1

I started using OOP in PHP for first time, and I dont know how to achieve the following structure for my variables:

$this->myData->generalData->title; $this->myData->generalData->description; $this->myData->amount; $this->myData->addNewData(); 

Up till now, what I am achieving is a normal variable inside a class:

$this->variablename 

I tried doing this code, but it's not working at all:

$this->CDNE = "CDNE"; $this->CDNE->FOLDER = "hello man"; 

Can you explain me, how all this works?

5
  • 2
    Well, obviously a property of a class (a "variable inside an object") can also hold an object, holding arbitrary content itself... So in your example $this->myData could be an object of another class holding the properties generalData and amount, also methods can be implemented in that object, ... Commented Nov 20, 2016 at 15:35
  • How to do that? Commented Nov 20, 2016 at 15:36
  • 1
    How do you assign an object to a variable? By assignment: $var = $object. Or directly by instantiation: $var = new myClass. This obviously is also possible inside an object, for example inside the class constructor: $this->var = new myClass;. Commented Nov 20, 2016 at 15:38
  • To build those kind of structures, personally I would use associative arrays instead of sub-objects. You could do: $this->cdne['content'] = "CDNE"; $this->cdne['folder'] = "hello man"; Commented Nov 20, 2016 at 15:42
  • It's a good solution to use Arrays, but as a beginner I still would like to know how to create sub objects. Commented Nov 20, 2016 at 15:49

1 Answer 1

1

Just to ilustrate my comment. Doing it with sub-objects could be something like this (a very basic example without attributes initialization):

class GeneralData{ public $title; public $description; } class MyData{ public $generalData; public $amount; function __construct(){ $this->generalData = new GeneralData(); } function addNewData(){ } } class MainClass{ public $myData; function __construct(){ $this->myData = new MyData(); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

I was just thinking about this example you gave me... In terms of performance what is better: One class with all configuration variables or modularised classes (around 4-5)?
@PHPLover It depends on so many things. You could take a look to "why to use OOP" articles, like these: stackoverflow.com/q/716412/3610018 stackoverflow.com/q/3232777/3610018 stackoverflow.com/q/2122123/3610018

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.