The if condition is throwing the following notice, how to fix this?
Notice: Trying to get property of non-object in /view_rep.php on line 17
Here is my php code
if ($check->check_area->id != #$_GET['check_area']) {
unset($check[$k]);
}
I tried the following but still, I can see multiple notices
error_reporting(0);
ini_set('display_errors',0);
Print_r($check), print thefollowing
[check_area] => stdClass Object
(
[id] => 5429140
[url] => /api/v2/checke_areas/5429140
[name] => Other
)
It seems $check is an array of object(s). If that's the case then change your if condition
if ($check->check_area->id ...
to
if ($check['check_area']->id ...
In order for $check->check_area->id to work:
$check must be an object with a property of check_area.
$check->check_area must be an object with a property of id.
One or both of these has not been met if you are getting a property of a non-object error.
Try checking whether they are objects before trying to access the property:
if ($check instanceof stdClass) {
}
Related
I'm trying to figure out a way to call a method of a specified member (Class A) coming from an array of members in class B.
<?php
class A
{
public function do_something()
{
echo "class A did something";
}
}
class B
{
private $arr = array();
private $current_index = 0;
public function add_new_A()
{
$new_a = new A;
array_push($this->arr, (object) [
$this->current_index => $new_a
]);
$this->current_index++;
}
public function get_an_A_by_index($index)
{
return $this->arr{$index};
}
public function do_something_with_A_member_inside_array($index)
{
self::get_an_A_by_index($index)->do_someting();
}
}
$b = new B;
$b->add_new_a();
$b->add_new_a();
echo print_r($b->get_an_A_by_index(0));
echo "\n";
$b->do_something_with_A_member_inside_array(0); // returns error
// console:
// stdClass Object ( [0] => A Object ( ))
// Uncaught Error: Call to undefined method stdClass::do_something();
?>
To wrap things up, I want to know if my approach is considered bad and/or if there is something I can do to fix the error. Before you disagree with my code, take a look at my php code I'm actually working on. That's all for my question.
Now about why I want to call a method of a member A inside . For my assignment I want a program that does something seperately with the method do_something of class a. So far, the only way to do that is by storing seperate members of A.
I'm not sure if I'm approaching this wrong or not, because I'm coming from Java. So, The first thing I came up with was the approach shown above. When I do this in Java, it works fine. But php is different from Java and I'm still learning how php works since I'm new to it.
Your code isn't far off, you've just got an issue with the way you're building up the collection of A objects.
array_push($this->arr, (object) [
$this->current_index => $new_a
]);
This is creating a data structure that I'm pretty sure isn't what you expect. You'll end up with an array full of stdClass objects, each with a single A member and its own internal index:
Array
(
[0] => stdClass Object
(
[0] => A Object
(
)
)
)
You're then retrieving the stdClass object and trying to run the method on that, hence the Call to undefined method stdClass::do_something... error you're seeing.
Instead, all you need to do is this:
$this->arr[$this->current_index] = $new_a;
The rest of your code is just expecting an array of A objects, nothing nested any deeper.
I've put a full example here: https://3v4l.org/ijvQa. Your existing code had a couple of other typos, which are also fixed. You'll spot them easily enough if you turn on error reporting.
I have an array in yii2, and ocassionally it's only 1 single object that is not empty (all other element of array is empty) and I don't know which one is it. How can I either find the one that is not empty, or (my idea what I was trying), to create a new array, with array_filter (but I'm not sure if it works also with array of objects), to have only the one object in it.
if (count($ttepk) == 1) {
$ttep_filtered[] = array_filter($ttepk);
$id = $ttep_filtered[0]->id;
}
But it was also not working. I get the error message: PHP Notice – yii\base\ErrorException Trying to get property of non-object.
Before array_filter it looks like this:
Array
(
[3] => app\models\Model Object
(
after array_filter:
Array
(
[0] => Array
(
[3] => app\models\Model Object
(
So it seems, array_filter is not the one I need, or I use it the wrong way.
Can you please help me? Thank you!
You can try something like this
$filtered = array_filter($ttepk, function($item) {
return $item instanceof app\models\Model;
});
if (count($filtered) == 1) {
$id = reset($filtered)->id;
}
In PHP I'm returning the sum of two columns and getting back an object of:
stdClass Object ( [sum(`total`)] => 54.00 [sum(`word_count`)] => 90 )
I'm trying to loop through this with a foreach
foreach($Classified as $classified) {
echo $classified->total;
echo $classified->sum;
}
returns the error: Notice: Trying to get property of non-object. I suspect the sum is somehow throwing it off?
I'm trying to create associative array of objects from row result set with member id as the key, but getting some error.
addATravelog() is just a function of the class UserLogsAndSOS(), whose objects i want in array.
Here is what I tried:
class UserArraySet {
private $arrayOfUsers = array();
function createArrayForTravelogs($result) {
While($row = $result->next()) {
if(array_key_exists($row['id'], $this->arrayOfUsers)) {
$this->arrayOfUsers[$row['id']] = new UserLogsAndSOS();
}
$this->arrayOfUsers[$row['id']]->addATravelog($row['title'], $row['blog']); //line 72
}
}
}
On calling createArrayForTravelogs() from the object I got the following error
Here is the error I got:
Notice: Undefined index: 1 in C:\xampp\htdocs\site\classes\userprofile.php on line 72
Fatal error: Call to a member function addATravelog() on a non-object in C:\xampp\htdocs\site\classes\userprofile.php on line 72
Can someone please let me know how to achieve this, I want something like this:
Array (
[1] => objectUserLogsAndSOS1
[5] => objectUserLogsAndSOS2
....
)
where key is the member id from $row.
I also need to check if the key exists, then call a function of that particular object to add data to its member, if not then create an object and then call a function of that particular object to add data to its member.
Thanks
just read the error message: you only create UserLogsAndSOS if there is already an entry - otherwise you call addATravelog on null.
maybe you forgot the "!" in your if clause?
Because the array stays empty.
You only create a new UserLogsAndSOS when there already is an element with the provided ID in the arrayOfUsers. The exact opposite of what you probably wanted.
You're probably missing a ! to reverse the array_key_exist result.
if(!array_key_exists($row['id'], $this->arrayOfUsers)) {
$this->arrayOfUsers[$row['id']] = new UserLogsAndSOS();
}
You missed and '!' I think this is causing the error
This question already has answers here:
PHP check whether property exists in object or class
(10 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I get this warning in my error logs and wanted to know how to correct this issues in my code.
Warning:
PHP Notice: Undefined property: stdClass::$records in script.php on line 440
Some Code:
// Parse object to get account id's
// The response doesn't have the records attribute sometimes.
$role_arr = getRole($response->records); // Line 440
Response if records exists
stdClass Object
(
[done] => 1
[queryLocator] =>
[records] => Array
(
[0] => stdClass Object
(
[type] => User
[Id] =>
[any] => stdClass Object
(
[type] => My Role
[Id] =>
[any] => <sf:Name>My Name</sf:Name>
)
)
)
[size] => 1
)
Response if records does not exist
stdClass Object
(
[done] => 1
[queryLocator] =>
[size] => 0
)
I was thinking something like array_key_exists() functionality but for objects, anything? or am I going about this the wrong way?
if(isset($response->records))
print "we've got records!";
isset() is fine for top level, but empty() is much more useful to find whether nested values are set. Eg:
if(isset($json['foo'] && isset($json['foo']['bar'])) {
$value = $json['foo']['bar']
}
Or:
if (!empty($json['foo']['bar']) {
$value = $json['foo']['bar']
}
In this case, I would use:
if (!empty($response->records)) {
// do something
}
You won't get any ugly notices if the property doesn't exist, and you'll know you've actually got some records to work with, ie. $response->records is not an empty array, NULL, FALSE, or any other empty values.
You can use property_exists
http://www.php.net/manual/en/function.property-exists.php
If you want to use property_exists, you'll need to get the name of the class with get_class()
In this case it would be :
if( property_exists( get_class($response), 'records' ) ){
$role_arr = getRole($response->records);
}
else
{
...
}
Error control operator
In case the warning is expected you can use the error control operator # to suppress thrown messages.
$role_arr = getRole(#$response->records);
While this reduces clutter in your code you should use it with caution as it may make debugging future errors harder. An example where using # may be useful is when creating an object from user input and running it through a validation method before using it in further logic.
Null Coalesce Operator
Another alternative is using the isset_ternary operator ??. This allows you to avoid warnings and assign default value in a short one line fashion.
$role_arr = getRole($response->records ?? null);
The response itself seems to have the size of the records. You can use that to check if records exist. Something like:
if($response->size > 0){
$role_arr = getRole($response->records);
}
If think this will work:
if(sizeof($response->records)>0)
$role_arr = getRole($response->records);
newly defined proprties included too.