When I do a query in class A, I got all data already. class B need to use some of the data. I prefer pass part of the query result to B than do a new query in B. Class B will perform some jobs and the data will be changed in class B. How to pass the array $something_else to class B? Here is the classes:
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
}
}
It’s not clear where in B you’re needing
something_else, so let’s just add it as part of the constructor: Make the constructor function accept an additional parameter ofsomething_elseand save it to that class’ property:When A creates a B:
$this->_project_obj = new B( $this, $this->id, loggedin_user_id() );And when B needs to get the latest version of
something_elsefrom its parent A:$this->_parent->something_else