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?

rossanmol
  • 1,633
  • 3
  • 17
  • 34
  • 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, ... – arkascha Nov 20 '16 at 15:35
  • How to do that? – rossanmol Nov 20 '16 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;`. – arkascha Nov 20 '16 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";` – nanocv Nov 20 '16 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. – rossanmol Nov 20 '16 at 15:49

1 Answers1

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();
    }
}
nanocv
  • 2,227
  • 2
  • 14
  • 27
  • 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)? – rossanmol Nov 20 '16 at 16:01
  • @PHPLover It depends on so many things. You could take a look to "why to use OOP" articles, like these: http://stackoverflow.com/q/716412/3610018 http://stackoverflow.com/q/3232777/3610018 http://stackoverflow.com/q/2122123/3610018 – nanocv Nov 20 '16 at 16:12