jnbdz
jnbdz

Reputation: 4383

Change the output by using a extending method in PHP

Is it possible to do something like this in PHP?

Image::myMethod(); // returns array
Image::myMethod()->toSring(); // Returns a string built inside the method toString

So, in other words, is there a way for PHP to detect if the method is being extended by another method if yes it then returns the self/this?

Upvotes: 4

Views: 70

Answers (2)

bishop
bishop

Reputation: 39354

Codifying what I meant in comment, this will give you logically the same behavior, though the implementation details differ:

class Artifact extends ArrayObject {
    public function toString(): string {
        // custom stuff, use ArrayObject api to access underlying data
    }
}

class Image {
    public function myMethod(): Artifact {
        // generate your array data, then:
        return new Artifact($data);
    }
}

Upvotes: 4

Alex
Alex

Reputation: 4811

In general it's impossible. But you can implement pretty similar behaviour by making __toString() magic method and implementing ArrayAccess interface (and Iterator if you want to use it in loops).

Alas, the implementation might be pretty bulky.

class MyClass implements Iterator, ArrayAccess 
{
    ...
    public function __toString() { ... }
    public function current ( ) { ... }
    public function key ( )  { ... }
    public function next ( ) { ... }
    public function rewind ( ) { ... }
    public function valid ( ) { ... }
    public function offsetExists ( $offset ) { ... }
    public function offsetGet ( $offset ) { ... }
    public function offsetSet ( $offset , $value ) { ... }
    public function offsetUnset ( $offset ) { ... }
}

function myFunc()
{
    return new MyClass(...);
}

(string)myFunc() // returns string value
myFunc()[0]  // access as array
foreach (myFunc() as $value) // iterate as array

Upvotes: 1

Related Questions