Как получить доступ к переменной одного класса из другого класса? - PullRequest
0 голосов
/ 21 января 2012

У меня такая ситуация:

// Object Class
class Person_Object {

   protected $_id;

   public function __construct( $id = null ) {
      $this->_id = $id;
   }

   public function getMapper() {
        $mapper = new Person_Mapper();
        return $mapper;
   }

   public function printIdInMapper() {
       $this->getMapper()->printIdInMapper();
   }

}

// Mapper Class
class Person_Mapper {

    public function printIdInMapper() {
       // How to access Person_Object's id here and echo id?
   }
}


// Code
$personModel = new Person_Object(10);
$personModel->printIdInMapper(); // should print 10

Теперь, как отобразить Person_Object's id value 10 в printIdInMapper() функции здесь

Ответы [ 2 ]

2 голосов
/ 21 января 2012

Попробуйте это:

// Object Class
class Person_Object {

   protected $_id;

   public function __construct( $id = null ) {
      $this->_id = $id;
   }

   public function getId() {
        return $this->_id;
   }

   public function getMapper() {
        $mapper = new Person_Mapper($this);
        return $mapper;
   }

   public function printIdInMapper() {
       $this->getMapper()->printIdInMapper();
   }

}

// Mapper Class
class Person_Mapper {
    $_person

    public function __construct( $person ) {
       $this->_person = $person
    }

    public function printIdInMapper() {
       echo $this->_person->getId();
   }
}
1 голос
/ 21 января 2012

Немного другой подход:

class Person_Object {

   protected $_id;

   public function __construct( $id = null ) {
      $this->_id = $id;
   }

   public function getId() {
       return $this->_id;
   }

   public function getMapper() {
        $mapper = new Person_Mapper();

        $mapper->setPerson($this);

        return $mapper;
   }

   public function printIdInMapper() {
       $this->getMapper()->printIdInMapper();
   }

}

// Mapper Class
class Person_Mapper {

    protected $person;

    public function setPerson(Person_Object $person) {
        $this->person = $person;
    }

    public function getPerson() {
        return $this->person;
    }

    public function printIdInMapper() {
       echo $this->getPerson()->getId();
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...