Why doesn't new operator creates chain structure?
-
24-05-2021 - |
Question
Assuming GeneralNews()
returns this
and CreateInstance()
return this
, the first 2 methods work but the final one fails.
I'm not understanding why?
$objGeneralNews = new GeneralNews();
$arrDataList = $objGeneralNews->SetWhere('news01date="2011-01-01"')->GetFrontList();
var_dump( $arrDataList ); //This method works
$arrDataList = GeneralNews::CreateInstance()->SetWhere('news01date="2011-01-01"')->GetFrontList();
var_dump( $arrDataList ); //This method works
$arrDataList = (new GeneralNews())->SetWhere('news01date="2011-01-01"')->GetFrontList();
var_dump( $arrDataList ); //This method doesn't works
Class Code GeneralNews:
class GeneralNews {
public function GeneralNews(){
return this;
}
public static function CreateInstance(){
$strClassName = 'GeneralNews';
return new $strClassName;
}
}
Solution
Indeed, directly referencing objects of new
expressions does not work in PHP 5.3, but does work in PHP 5.4.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow