I know this is common error and I have read all answer but my case looks different, at least as a PHP newbie so kindly don't decide action based on question subject.
I have a PHP code which working but I am trying to arrange it in appropriate functions, as in below code but I get following error Warning: Creating default object from empty value in /home/abc/vhosts/localhost/public/portfolio.php on line 16
:
<?php
// configuration
require("../includes/config.php");
// prepare portfolio object
$portfolioObject = (object) ["portfolioSummaryArr" => [], "cashInHand" => ""];
function getCashInHand(){
// query database to get cash in hand
$rows = CS50::query("SELECT cash FROM users WHERE username = ?", $_SESSION["username"]);
// get first (and only) row
$row = $rows[0];
$portfolioObject->cashInHand = $row["cash"];
$portfolioObject->portfolioSummaryArr = [11, 22, 33, 44, 55];
}
getCashInHand();
?>
Now after reading all the answers and documentation I think I need some sort of object first so I did this and then I get this error Parse error: syntax error, unexpected '$myObject' (T_VARIABLE) in /home/abc/vhosts/localhost/public/portfolio.php on line 12
. I trusted this because something similar is allowed in JS and it works, but guess in PHP isn't so my guess is that using objects created like this you cannot define or access function.
$myObject = new stdClass();
$myObject->demoFunction = function(){
echo "I am coming from demo function.";
}
$myObject->demoFunction();
To me things get more interesting because if I do as in below in my code just after require("../includes/config.php");
then it works and no error, but function definition and access as shown in my first code snippet doesn't work.
// Defining function
function whatIsToday(){
echo "Today is XXX";
}
// Calling function
whatIsToday();