0

クラスAでクエリを実行すると、すでにすべてのデータが取得されています。クラスBは一部のデータを使用する必要があります。Bで新しいクエリを実行するよりも、クエリ結果の一部をBに渡す方が好きです。クラスBはいくつかのジョブを実行し、データはクラスBで変更されます。配列$something_elseをクラスBに渡す方法は?クラスは次のとおりです。

class A{
  public $something;
  private $_project_obj;
  function __construct( $id = null ){
    if ( $id ) {
       $this->id = $id;
       $this->populate( $this->id );
    }
}
 function populate(){
      $query = //do query
      $this->somthing= $query['A'];
      $this->something_else = $query['B'];
}
 function save(){
     // call save() in class B, $something_else is saved there
     if ( $this->_project_obj instanceof B ) {
    if ( true !== $this->_project_obj->save() ) {
        return false;
    }
    }
    // save $something and other stuffs in class A
   //  ......
   }
  function project() {  
    if ( !$this->_project_obj instanceof B ) {
     if ( ( $this->id ) && ( loggedin_user_id() ) ) {
       $this->_project_obj = new B( $this->id, loggedin_user_id() );
    } else {
    return false;
    }
    }
     return $this->_project_obj
    }
}
class B{
  public $data_this;
  public $data_that;
  function __constructor( $id=null, $user_id=null){
      if($id && $user_id){
        return $this->populate();
      }
      return true;

  }
 function populate(){
  $query = // do the same query as in class A
  $something_else = $query['B'];
  $this->data_this = $something_else['a'];
  $this->data_that = $something_else['b'];
 }
 function save(){
  // save all data as $something_else 
 }
 function jobs(){
 // perform jobs
 }
}
4

2 に答える 2

0
class class_b
{

public $something_else = NULL

}

$a = new class_a();
$b = new class_b();

$b->something_else = $a->something_else
于 2012-09-14T04:08:12.487 に答える
0

Bのどこに必要なのかが明確ではないsomething_elseので、コンストラクターの一部として追加しましょう。コンストラクター関数にの追加パラメーターを受け入れさせ、something_elseそのクラスのプロパティに保存します。

class B{
  private var $_parent;
  function __constructor( $parent, $id=null, $user_id=null){
      $this->_parent = $parent; // Save reference to the "A" that contains this "B"
      if($id && $user_id){
        return $this->populate();
      }
      return true;

  }

AがBを作成するとき:$this->_project_obj = new B( $this, $this->id, loggedin_user_id() );

something_elseそして、Bがその親Aから最新バージョンを取得する必要がある場合:$this->_parent->something_else

于 2012-09-14T04:10:39.033 に答える