1

Does php support operator overloading?

I'm trying to create a class that takes in a date and I'd like to compare it with another object without having to use methods or properties.

This is what I'm trying to do:

$obj1 = new myClass('2016-08-15');
$obj2 = new myClass('2016-02-06');

if ($obj1 > $obj2){
    ...
}

I know how to do the date comparison, all I need to know is how to overload the operators >, < and ==.

Thanks.

3 Answers3

1

PHP doesn't support operator overloading.

There is an ancient extension which allowed to do this in a manner similar to python. You can find it here.

That being said, your best bet nowadays is to just use regular methods for comparison.

Kuba Birecki
  • 2,926
  • 1
  • 13
  • 16
  • It seems that it is still possible to [overload the array subscript operator](https://stackoverflow.com/questions/7586746/can-i-overload-an-array-subscript-operator-in-php) using the `ArrayAccess` interface. – Anderson Green Sep 11 '21 at 18:59
0

PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.

I hope this link will help you to understand concept,

http://php.net/manual/en/language.oop5.overloading.php

Vasim Shaikh
  • 4,485
  • 2
  • 23
  • 52
0

You can use pecl-php-operator to overload operator.

git clone https://github.com/php/pecl-php-operator
cd pecl-php-operator
phpize
./confiure
make && make install
echo "extension=operator.so" > /etc/php/7.2/mods-available/operator.ini
ln -s /etc/php/7.2/mods-available/operator.ini /etc/php/7.2/cli/conf.d/20-operator.ini
ln -s /etc/php/7.2/mods-available/operator.ini /etc/php/7.2/fpm/conf.d/20-operator.ini
service php7.2-fpm reload
shtse8
  • 1,092
  • 12
  • 20