IT Share you

PHP에서 연산자를 오버로드 할 수 있습니까?

shareyou 2020. 11. 27. 21:43
반응형

PHP에서 연산자를 오버로드 할 수 있습니까?


특히 Array 클래스를 만들고 [] 연산자를 오버로드하고 싶습니다.


PHP5를 사용하는 경우 (사용해야하는 경우) SPL ArrayObject 클래스를 살펴보십시오 . 문서가 너무 좋지는 않지만 ArrayObject를 확장하면 "가짜"배열을 갖게 될 것이라고 생각합니다.

편집 : 여기에 내 간단한 예가 있습니다. 그래도 귀중한 사용 사례가 없습니다.

class a extends ArrayObject {
    public function offsetSet($i, $v) {
        echo 'appending ' . $v;
        parent::offsetSet($i, $v);
    }
}

$a = new a;
$a[] = 1;

실제로 최적의 솔루션은 ArrayAccess 인터페이스의 네 가지 방법을 구현하는 것입니다. http://php.net/manual/en/class.arrayaccess.php

'foreach'컨텍스트에서 개체를 사용하려면 'Iterator'인터페이스를 구현해야합니다. http://www.php.net/manual/en/class.iterator.php


과부하 및 운영자의 PHP의 개념은 (참조 과부하배열 연산자를 ) C ++의 개념으로하지 않습니다. +,-, [] 등과 같은 연산자를 오버로드하는 것이 가능하다고 생각하지 않습니다.

가능한 해결책


PHP 5.0 이상에서 간단하고 깨끗한 솔루션을 얻으 려면 ArrayAccess인터페이스 를 구현하고 offsetGet, offsetSet, offsetExists 및 offsetUnset 함수를 재정의 해야합니다 . 이제 객체를 배열처럼 사용할 수 있습니다.

예:

<?php
class A implements ArrayAccess {
    private $data = array();

    public function offsetGet($offset) {
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
    }

    public function offsetSet($offset, $value) {
        if ($offset === null) {
            $this->data[] = $value;
        } else {
            $this->data[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->data[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->data[$offset]);
    }
}

$obj = new A;
$obj[] = 'a';
$obj['k'] = 'b';
echo $obj[0], $obj['k']; // print "ab"

It appears not to be a feature of the language, see this bug. However, it looks like there's a package that lets you do some sort of overloading.


Put simply, no; and I'd suggest that if you think you need C++-style overloading, you may need to rethink the solution to your problem. Or maybe consider not using PHP.

To paraphrase Jamie Zawinski, "You have a problem and think, 'I know! I'll use operator overloading!' Now you have two problems."

참고URL : https://stackoverflow.com/questions/787692/is-it-possible-to-overload-operators-in-php

반응형