Table of Contents
Overview
- Scalars are passed by values
- To pass Scalars by reference you need to use the & Reference Operator
- Objects are passed by Reference
PHP sample Code
class WRLoginObj { public $pvName = ""; public $isOnline = false; function __construct($pvName, $isOnline ) { $this->pvName = $pvName; $this->isOnline = $isOnline; } } $wrLoginObjArr = []; initApp(); function initApp() { $isOnline = "false"; $wrLoginObjArr = []; $wrLoginObj = new WRLoginObj("PV1", "false" ); array_push( $wrLoginObjArr, $wrLoginObj ); $wrLoginObj = new WRLoginObj("PV2", "false" ); array_push( $wrLoginObjArr, $wrLoginObj ); echo("Object Test: Objects/Arrays are passed by reference\n"); dumpObjData($wrLoginObjArr); changeObjData($wrLoginObjArr); dumpObjData($wrLoginObjArr); echo("Scalar before changeSclar() [ Original Value ] - isOnline: " .$isOnline . "\n" ); changeSclarCopyByWrite($isOnline); echo("Scalar after changeSclarCopyByWrite [ Nothing changed ] - isOnline: " .$isOnline . "\n" ); changeScalarbyRef($isOnline); echo("Scalar after changeScalarByRef() [ Changed value ] - isOnline: " .$isOnline . "\n" ); } function changeScalarByRef(&$val) { $val = "true"; } function changeSclarCopyByWrite($val) { $val = "true"; } function dumpObjData($loginArr) { foreach ($loginArr as $loginObj) { echo ("pvName: " . $loginObj->pvName . " - Status: ". $loginObj->isOnline . "\n") ; } } function changeObjData($loginArr) { foreach ($loginArr as $loginObj) { $loginObj->isOnline = "true"; } }
PHP Program Output
D:\xampp\htdocs\tc> php objRef.php Object Test: Objects/Arrays are passed by reference pvName: PV1 - Status: false pvName: PV2 - Status: false pvName: PV1 - Status: true pvName: PV2 - Status: true Scalar before changeSclar() [ Original Value ] - isOnline: false Scalar after changeSclarCopyByWrite [ Nothing changed ] - isOnline: false Scalar after changeScalarByRef() [ Changed value ] - isOnline: true