Object Properties in PHP and Python

#tech - 3 Minute Read

Object-oriented design is a major achievement in software. It's a creative and powerful use of memory allocation.

When programmers want to move from using one language to another, a common question is asked: "is (name of cool new language) object-oriented?"

If the answer is "yes", programmers might feel right at home. But each programming language is different. In general, every language has a unique reason for being, and therefore, implementations of core features can be very different—especially the implementation of objects.

Here we take a look at a key difference in PHP versus Python objects. We'll create equivalent classes in each language, and then instantiate some objects and compare their behavior.

Equivalent classes

Here's a basic class MyClass, which has a property data to store some values. For the sake of example, we'll leave out constructors for now.

PHP

class MyClass
{
    public $data = [];
}

Python

class MyClass:
    data = []

Adding data

Let's make two objects, one to store fruits apple and banana and one to store a carrot.

PHP

$object_one = new MyClass();
$object_one->data[] = 'apple';
$object_one->data[] = 'banana';
print_r($object_one->data);

$object_two = new MyClass();
$object_two->data[] = 'carrot';
print_r($object_two->data);

Python

object_one = MyClass()
object_one.data.append('apple')
object_one.data.append('banana')
print(object_one.data)

object_two = MyClass()
object_two.data.append('carrot')
print(object_two.data)

Output

In PHP, we have printed:

Array
(
    [0] => apple
    [1] => banana
)
Array
(
    [0] => carrot
)

But in Python, we have:

['apple', 'banana']
['apple', 'banana', 'carrot']

Conclusion

How is it that object_two in Python contains the data of object_one? This is due to Python's OOP feature class attributes, which are meant not to store default values for objects, but to store data that all objects will share. In PHP, we might think of this as like a class constant. Yet in Python, class attributes can be changed.

To limit data to an instance attribute in Python, we write instead:

class MyClass:
    def __init__(self):
        self.data = []

... and with the same usage code above, we'd get the same output as in PHP:

['apple', 'banana']
['carrot']

There are some cases where Python's class attributes are useful:

  • Constants that aren't meant to change.
  • A counter that is incremented after objects are instantiated or run a function.
  • Other data types that keep track of instantiated objects.

In short, it pays to know the differences between the way a language implements the concept of objects. There may be differences in property visibility which can lead to drastically different results in your application.


Updated May 22, 2020.