php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #76939 Arithmetic operations and assignment magic methods
Submitted: 2018-09-26 19:46 UTC Modified: 2018-09-26 20:16 UTC
From: henrique dot borba dot dev at gmail dot com Assigned:
Status: Suspended Package: Math related
PHP Version: Next Major Version OS:
Private report: No CVE-ID: None
 [2018-09-26 19:46 UTC] henrique dot borba dot dev at gmail dot com
Description:
------------
While developing a NumPy equivalent for PHP (using C) I came across a limitation. I coulnd't perform arithmetic operations with objects, so a code like this is impossible (wich is possible with NumPy):

$a = CArray::fromArray($arr);
$result = $a + $a;

I was thinking about the possibility of a new magic method that would intercept the arithmetic operations:

class CArray
{
    ...

    public function __arithmetic($operator, $operand)
    {
        if($operator == PHP_ADD_OP) {
            return self::add($this, $operand);
        }
        ...
    }
}

consequently the code below would also be valid if the class were used in conjunction with __offsetGet:

$b = CArray::fromArray([]);
$a = CArray::fromArray([0, 2, 1, 0]);
$b[$a - 1];

Also, assignment magic method would be useful in some situations relative to C pointer index within PHP Objects (like a PHP Object pointing to an C array position in memory using an extension):

function test($a)
{
    $b = $a; // POINTS TO 0
    $c = $b; // POINTS TO 0
    return $c; // POINTS TO 0
}

$arr = CArray::fromArray([1, 2]);  // UUID: 0
test($arr);
// GC RUNS AND FREE $b
// $arr is not freed, but its pointer was freed with $b
// any operations with $arr will cause memory troubles

If $arr has a pointer to a C buffer and contains an __destruct method that free that buffer position, when GC runs
the code above it should cause seg faults or memory leaks. During assignment all ($a, $b, $c, $arr) got the same
values of $arr (wich contains the [1, 2] array position in memory), instead, it should be capable of "clone" this 
array to a new memory position and retrieve a new pointer, so $b, $c and $a would all be equal to $arr but in different
memory positions.

I guess __assign($value) magic method would solve this, by assigning to the object the return of this method, writing over it.

Sorry about my bad english, I hope you guys got the idea.



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-09-26 20:16 UTC] requinix@php.net
-Status: Open +Status: Suspended
 [2018-09-26 20:16 UTC] requinix@php.net
A matter like this is too complicated to deal with on this lowly bug tracker, and there are already multiple competing ideas on how to approach the problem. Check out the RFC process.
https://wiki.php.net/rfc/howto
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Oct 31 22:01:27 2024 UTC