如何从其他类访问一个类的变量?

时间:2012-01-20 20:19:41

标签: php zend-framework class object

我有这样的情况:

// 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 个答案:

答案 0 :(得分:2)

试试这个:

// 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 :(得分:1)

略有不同的方法:

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();
   }
}