Pergunta

First of all - my English is bad so I hope you will understand. I have question involving method chaining on nested objects structure.

I'm trying to create some kind of a list with objects and sub lists that create itself on the fly. So far i have this code:

interface IData {}


class root {
    public function __construct( root $proxy = null ) {
        $this->proxy = $proxy;
    }
    public function __destruct() {
        if( !is_null( $this->proxy ) ) {
            unset( $this->proxy );
        }
    }
    public function OpenList() {
        $list = new field_list( $this );
        $this->data[] = $list;
        return $list;
    }

    public function CloseList() {
        return $this->proxy;
    }

    public function Add() {
        $this->data[] = new field();
        return $this;
    }


    private $proxy = null;
    private $data = array();
}

class field_list extends root implements IData {
    public function __construct( root $proxy ) {
        parent::__construct( $proxy );
    }
    public function __destruct() {
         parent::__destruct();
    }
}

class field implements IData {}

I'm using my code as follows:

$root = new root();
$root->OpenList()->Add()->CloseList()->OpenList()->Add()->Add()->Add()->OpenList()->Add();

I can append to $root field objects (class field), but also open new lists (class field_list) and append field objects to the last opened list.

I wonder if the object reference i created ($proxy) will cause memory leak problems, and also if there are any performance issues with this code. (EDIT:) when i print_r($root); I'm getting recursion in the output, and I don't know if it's some type of a problem with my objects structure.

root Object(
[proxy:root:private] => 
[data:root:private] => Array
    (
        [0] => field_list Object
            (
                [proxy:root:private] => root Object
  *RECURSION*
                [data:root:private] => Array
                    (
                        [0] => field Object
                            (
                            )

                    )

            )

        [1] => field_list Object
            (
                [proxy:root:private] => root Object
  *RECURSION*
                [data:root:private] => Array
                    (
                       ........
                    )

            )

    )

)

Thank you

Foi útil?

Solução

I've seen chained method calls before, and I don't think that I've ever encountered any issues. In terms of memory leaks, I doubt there is a problem because unlike in languages like C++ or Java, you don't have to deal with the memory. You've taken care to write a destructor, so I doubt there will be a problem.

Since you are creating only 1 instance, it should only refer to 1 instance of the property $proxy, so I'm thinking this could be OK.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top