Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP using objects instead of arrays

Tags:

oop

php

When I started to learn OOP programming I read that everything is an object. For the most time I develop in PHP. Arrays have important role here. In languages like C# in most cases you really have to use and pass objects not arrays.

For example:

Class Product
{
    private $data = array();

    public function __construct()
    {
        $this->data['setting_1'] = 'a';
        $this->data['setting_2'] = 'b';
        $this->data['setting_3'] = 'c';
        $this->data['setting_4'] = 'd';
        $this->data['setting_5'] = 'e';

    }
}

Is there any sense to create classes for everything when you use PHP? For example:

Class Product
{
    private $setting_1, $setting_2,  $setting_3,  $setting_4,  $setting_5; 
}

And then instantiate class Product in another class (eg. Model) and return object instead of array (eg. to Controller)?

like image 815
webrama.pl Avatar asked Dec 27 '22 01:12

webrama.pl


1 Answers

The answer is simple.

Everything is an object

is just an ideal.

In most real world OOP languages there are simple data types as well. Even in Java or CSharp. In PHP there is even an array as a complex, non object data type. You should not worry using it, also in OOP context of course.

Note that having the powerful array data type is more an advantage than a disadvantage. In my opinion the most lacking OOP feature of PHP is polymorphism, btw.


However, PHP5 introduced a suite of iterators and data structures, in the so called Standard PHP Library (SPL) extension, which is part of the PHP core distribution. You can have a look at them, but in most cases the array data type should work well (and performant).

like image 73
hek2mgl Avatar answered Jan 12 '23 14:01

hek2mgl