当我在类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
}
}
不清楚在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() );
时
当B需要从其父级A获得something_else
的最新版本时:$this->_parent->something_else
class class_b
{
public $something_else = NULL
}
$a = new class_a();
$b = new class_b();
$b->something_else = $a->something_else