2

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.

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It seems that it is still possible to overload the array subscript operator using the ArrayAccess interface.
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.