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();
It was just matter of time, I would say. I had to do some reading to understand leverage the object orientation of PHP. Below is how I could resolve all my PHP errors and warnings. Needless to say my favorite debugging methodology "print to screen/terminal", in case of PHP using echo helped a lot.
<?php
// configuration
require("../includes/config.php");
class portfolio{
public $portfolioObject;
public function __construct(){
echo "__construct()</br>";
$this->portfolioObject = new stdClass();
}
public function initialize(){
echo "initialize()";
$portfolioObject = (object) ["portfolioSummaryArr" => [], "cashInHand" => ""];
}
public 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];
$this->portfolioObject->cashInHand = $row["cash"];
$this->portfolioObject->portfolioSummaryArr = [11, 22, 33, 44, 55];
}
public function setSessionObject(){
$_SESSION["portfolioSummaryResults"] = $this->portfolioObject;
}
}
$myPortfolio = new portfolio();
$myPortfolio->initialize();
$myPortfolio->getCashInHand();
$myPortfolio->setSessionObject();
render("portfolio/portfolio_results.php", ["title" => "Portfolio"]);
?>
Related
I am trying to implement a logging library which would fetch the current debug level from the environment the application runs in:
23 $level = $_SERVER['DEBUG_LEVEL'];
24 $handler = new StreamHandler('/var/log/php/php.log', Logger::${$level});
When I do this, the code fails with the error:
A valid variable name starts with a letter or underscore,followed by any number of letters, numbers, or underscores at line 24.
How would I use a specific Logger:: level in this way?
UPDATE:
I have tried having $level = "INFO" and changing ${$level} to $$level. None of these changes helped.
However, replacing the line 24 with $handler = new StreamHandler('/var/log/php/php.log', Logger::INFO); and the code compiles and runs as expected.
The variable itself is declared here
PHP Version => 5.6.99-hhvm
So the answer was to use a function for a constant lookup:
$handler = new StreamHandler('/var/log/php/php.log', constant("Monolog\Logger::" . $level));
<?php
class Logger {
const MY = 1;
}
$lookingfor = 'MY';
// approach 1
$value1 = (new ReflectionClass('Logger'))->getConstants()[$lookingfor];
// approach 2
$value2 = constant("Logger::" . $lookingfor);
echo "$value1|$value2";
?>
Result: "1|1"
I am customising a opensource phreebooks. I want to change the module names in that. I did change the module names for phreebooks and phreedom successfully, but when i change the name for phreedom i can not print any pdf. I am getting this error
User: 1 Company: phree RUN-TIME WARNING: 'Creating default object from empty value' line 50 in file
F:\wamp\www\phree\modules\report\pages\popup_gen\pre_process.php
In line no 50, code is like this
if (isset($_GET['xfld'])) $report->xfilterlist[0]->fieldname = $_GET['xfld'];
Can somebody please tell me where exactly i am doing wrong. I have been tying it from past 3 days.
EDITED
if (isset($_GET['xfld'])) { // check for extra filters
if (!isset($_GET['xfld'])) $xfld = new stdClass();
echo "BLANK";
if (isset($_GET['xfld'])) $report->xfilterlist[0]->fieldname = $_GET['xfld'];
if (isset($_GET['xcr'])) $report->xfilterlist[0]->default = $_GET['xcr'];
if (isset($_GET['xmin'])) $report->xfilterlist[0]->min_val = $_GET['xmin'];
if (isset($_GET['xmax'])) $report->xfilterlist[0]->max_val = $_GET['xmax'];
}
i did like this
It displays "BLANK" but actually isset($_GET['xfld'] is SET from URL.
$_GET['xfld'] = $xfld;
$xfld = NULL;
$xfld->success = false; // Warning: Creating default object from empty value
PHP will report a different error message if $xfld is already initialized to some value but is not an object:
$xfld = something;
$xfld->success = false; // Warning: Attempt to assign property of non-object
You shoud check whether the object already exists:
if (!isset($_GET['xfld'])) $xfld = new stdClass();
Otherwise, this code is not an equivalent replacement for the "old PHP" implicit object creation.
I am new in this site, and i found some questions that are connected to my system error but unfortunately they can't fix the error. I am creating an offline web-based information system for my capstone project and I don't understand why P_Bday is undefined.. Here is my code
This is my code for inputting Birthdate:
input type="text" id = "P_Bday" name = "P_Bday" class="form-control" data-inputmask="'alias': 'dd/mm/yyyy'" data-mask placeholder="dd/mm/yyyy" required
And here's my code for calculating age:
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}
$dob = $_POST["P_Bday"];
And I call my function here, where it should display the calculated age depending on the inputted birthdate:
input type='text' name = 'P_Age' id='disabledTextInput' class='form-control' value='".ageCalculator($dob)."' readonly
Every time I ran my code it says:
Notice: Undefined index: P_Bday in
C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php on line
47
If the line $dob = $_POST["P_Bday"]; is being run on the page before anything is sent via POST, then $_POST[foo] is invalid.
Change the line to:
if(isset($_POST["P_Bday"])) $dob = $_POST["P_Bday"];
else $dob = null;
Or:
$dob = isset($_POST["P_Bday"]) ? $_POST["P_Bday"] : null;
An Undefined index error is pretty simple to debug. You start at the file mentioned in the error message C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php and go to the line mentioned in the error message line 47 and find the undefined index in question on that line P_Bday and know with absolute certainty that up to this point in your code you have not defined that index for that variable. You can work your way backwards through the code to try and figure out your mistake. The mistake can be a typo (you used the wrong case/variable name) or it can be that you just forgot to initialize the variable properly.
The best way to avoid undefined variable/index errors is to initialize always and initialize early. In the few cases where you cannot be sure that variables are properly initialized (for example with $_POST/$_GET or other external variables under control of client input) you want to use isset to avoid the error and that way you can coalesce null values or write logic that prevents the code from continuing with an uninitialized value in case of user error.
Example
if (!isset($_POST['P_Bday'])) {
die("You forgot to fill out your birthday!");
} else {
echo "Yay!";
}
Some good initialization techniques with $_POST/$_GET
A good best practice for "initialize always and initialize early" when dealing with user input is to setup a default set of values for the expected input from your form and initialize from that in order not to fall into this trap.
Example
$defaultValues = [
'P_Bday' => null,
'Option1' => 'default',
'Option2' => 1,
];
/* Let's say the user only supplied Option1 */
$_POST = ['Option1' => 'foo'];
/* This makes sure we still have the other index initialized */
$inputValues = array_intersect_key($_POST, $defaultValues) + $defaultValues;
/**
* Now you can pass around $inputValues safely knowing all expected values
* are always going to be initialized without having to do isset() everywhere
*/
doSomething(Array $inputValues) {
if (!$inputValues['P_Bday']) { // notice no isset() check is necessary
throw new Exception("You didn't give a birthday!!!");
}
return (new DateTime)->diff(new DateTime($inputValues['P_Bday']))->y;
}
You are declaring the variable $dob after calling function. You have to declare your variable before function call and also use conditional statement like following:
Please write your code as follows:
if(isset($_POST["P_Bday"])){
$dob = $_POST["P_Bday"];
} else {
$dob ="";
}
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}
I am occasionally getting the PHP Fatal error: Call to undefined method stdClass::transition() in agent.php on line 25 (I marked line 25 in the code). This code is called often, so struggling to see why it is happening.
Here is the snippet of agent.php that calls the
function agent_exam_complete($exam){
$ce = $exam->educational();
$ce->exam_id = $exam->exam_id;
$ce->exam_grade = $exam->score;
$ce->exams_remaining -= 1;
$ce->exam_received_date = sql_now();
if($exam->status()=='passed'){
$ce->transition('passed');
}elseif($ce->exams_remaining <= 0){
$ce->transition('failed');
}
$ce->save();
if($ce->is_certification_completed($ce->certification_id, $ce->client_no)){
agent_certification_complete($ce->certification_id, $ce->client_no);
}
}
function agent_certification_complete($certification_id, $client_no){
$ce = ClientPurchase::find('first', array('conditions' => "certification_id = '$certification_id' and is_certification = 1 and client_no='$client_no'"));
$ce->certification_date = date('Y-m-d');
$ce->transition('passed'); **//Line 25**
$ce->save();
}
transition() is defined in another file and is called often. I've included a little bit of it's code just for flavor.
function transition($event_tag){
$old_status = $this->status;
$next_status = $this->next_status_for_transition($event_tag);
if($next_status==''){
return; }
$this->status = $next_status;
My question is, why am I only getting this error periodically and not all the time? What can I do to eliminate the error and subsequent blank screen for my clients? I've only noticed that it is happening to those with Firefox or Chrome.
Thanks in advance,
Jim
The object $ce that contains the function is being generated multiple times. I suppose this is so transition is customized for whatever object is called.
Why not create another object for re-useable functions? Consider expanding the function so that it is compatible with all objects that would use it.
$my = new functionClass;
class functionClass
{
function transition()
{
$old_status = $this->status;
$next_status = $this->next_status_for_transition($event_tag);
if($next_status==''){
return; }
$this->status = $next_status;
}
}
$my->transition( 'passed' );
Something like that would cut down on unpredictability and I believe may solve your problem.
Try this little snippet of code to see whats going on:
$ce = false;
$ce->certification_date = date('Y-m-d');
var_dump($ce);
In this case $ce get cast to an object of stdClass when you try to set a property (certification_date).
Now your code:
function agent_certification_complete($certification_id, $client_no){
$ce = ClientPurchase::find('first', array('conditions' => "certification_id = '$certification_id' and is_certification = 1 and client_no='$client_no'"));
//$ce is probably false or null
//it gets cast to a stdClass object
$ce->certification_date = date('Y-m-d');
//stdClass does not have a transition method; ERROR
$ce->transition('passed'); **//Line 25**
$ce->save();
}
So in your code, if find() is returning null or false, or maybe some other choice values, $ce gets cast to a stdClass object on the next line. Then that stdClass object does not have a transition() method so you get an error.
To fix this, either adjust your find method or check its return value and handle accordingly.
As to it happening only in certain browser, I think thats a false conclusion. If find() is calling a query, it probably only happens at certain times depending on the result of that query.
I'm trying to reset the pointer to the first record in CodeIgniter. Consider the following greatly simplified code:
$query_milestones = "SELECT * FROM milestones";
$milestones = $this->db->query($query_milestones);
foreach($milestones->result() as $milestoneRow){
// do something
}
$milestones->data_seek(0); // <--- This gives me Fatal error.
foreach($milestones->result() as $milestoneRow){
// do something else
}
This gives me:
Fatal error: Call to undefined method CI_DB_mysql_result::data_seek()
How can I do a mysql_data_seek with CodeIgniter?
UPDATE: It seems VERY odd to me but resetting the pointer apparently is not necessary. The following does what I want but not what I expect:
$query_milestones = "SELECT * FROM milestones";
$milestones = $this->db->query($query_milestones);
foreach($milestones->result() as $milestoneRow){
// do something
}
// As soon as the foreach is reached, the first record is retrieved again.
foreach($milestones->result() as $milestoneRow){
// do something else
}
try #$this->db->data_seek(0); instead of $milestones->data_seek(0);
You can try $milestones->_data_seek(0); but I have not used CodeIgniter in a while and supposedly it is a private method, at least it used to be.