P
P
pmvpro2020-09-04 17:20:54
PHP
pmvpro, 2020-09-04 17:20:54

How to pass parameters from one property-object to another property-object?

There is an object which has two properties - objects.
Is it possible to access from one property-object to another property-object. For example, in setPage() you need to get data from the property object $site->db;

<?php
 class page{
    public $path;
    public $code;
    function setPath($path){
        /*Здесь нужно получить доступ к методу getName объекта $site->db */
        $this->path=$path;    
    }
    function getPath(){
        $ret=$this->path;
        return $ret;    
    }
 }
 class db{
    public $name;
    function setName($name){
        $this->name=$name;
    }
    function getName(){
        return $this->name;
    }
 }
 class site {
    public $server;
    public $db;
    public $page;
    function dbInit(){
        $this->db= new db();
        $this->db->setName('local');
    }
    function getPage(){
        $this->page=new page();        
        $this->page->setPath('user/profile');
        echo $this->page->getPath();
    }
 }
 $site=new site();
 $site->dbInit();
 $site->getPage();

So far the only solution is to pass as a parameter. Well, respectively, add a constructor, etc. But if there are several such properties-objects, then what is the only way? Transfer all objects manually? Is it really any other way?
$this->page=new page($this->$db);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2020-09-04
@FanatPHP

It is not very clear how this differs from the situation when the objects are not properties of the same class. In my opinion, there is no difference. So yes - transfer all objects "manually". Good old dependency injection
And if there are several such properties-objects, then perhaps reconsider the structure of classes or how they are created. Enable factory or container

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question