Trying to access properties of the containing obje

2019-08-24 12:40发布

After hours looking for solutions and patterns, it's time for me to ask the pros.

I'd love to order my object in a logical hierarchy, but still want to be able to access properties of the parent object. A simple example how I'd love to have it work...

    class car {

       public $strType;  // holds a string
       public $engine;   // holds the instance of another class

       public function __construct(){
           $this->type = "Saab";
           // Trying to pass on $this to make it accessible in $this->engine
           $this->engine = new engine($this);
       }

    }

    class engine {

        public $car;

        public function __construct($parent){
            $this->car = $parent;
        } 

        public function start(){
            // Here is where I'd love to have access to car properties and methods...
            echo $this->car->$strType;
        }
    }

    $myCar = new car();
    $myCar->engine->start();

What I won't achieve is that a method in engine can access the 'parent' car properties. I managed to do so like this, but I believe that is very very ugly...

    $myCar = new car();
    $myCar->addParent($myCar);

From within the addParent MethodI would be able to pass the instance on to the engine object. But that can't be the clue, can it? Is my whole idea queer?

I don't want engine to inherit from car because a car has lots of methods and properties and engine has not. Hope you get what I mean.

Hoping for hints, Cheers Boris

标签: php class
1条回答
相关推荐>>
2楼-- · 2019-08-24 13:21

As @Wrikken mentioned, the correct syntax would be echo $this->car->strType;

type does not seem to be a member of car, but if you changed it the line to

$this->strType = "Saab";

Then the statement in question should now echo "Saab"

Though I think good practice here would be to not have the engine class contain a car object, just the car class should contain an engine object. And the properties would be better off as private. So you could have a car method like

public startEngine() {
    $success = $this->engine->start();
    if(success) {
        echo "Engine started successfully!";
    } else {
        echo "Engine is busted!";
    }
}

Where engine::start() returns a boolean.

查看更多
登录 后发表回答