PHP Trying to get property of non-object error in function - php

Need some help please. I am getting a 'Trying to get property of non-object' error in a function call that looks at an array.
The array I am calling is
$var = array(
"variableA" => "abc123",
"variableB" => "123456789"
);
The function I am using is
public function getJson($var)
{
$resource = sprintf("/info/%s/%s/json", $var->variableA, $var->variableB);
return $this->_restCall('GET', $resource);
}
I cant understand why the array values are not being passed through?
Could someone please help?

$var is an array not an object. So you need to use array syntax, not object syntax:
public function getJson($var)
{
$resource = sprintf("/info/%s/%s/json", $var['variableA'], $var['variableB']);
return $this->_restCall('GET', $resource);
}

Related

Passing an array as the parameter of a function in PHP

This is my array
$sub = array("English"=>"12","Hindi"=>"12","History"=>"12","Geography"=>"12","Mathematics"=>"12","Physics"=>"12","Chemistry"=>"12","Biology"=>"12");
Want to pass this entire array as the parameter of a function & want to sum up the marks(array values) using the function
function sum_marks($sub){--Function body--
}
I don't know if this is the proper syntax for passing an array to a function, help!!
Is this you are looking for?
$mySum = array_sum($sub);
Yes, it is the appropriate syntax for passing an array as an argument to a function.
However, you might consider adding a type declaration for the $sub argument:
function sum_marks(array $sub)
{
return array_sum($sub);
}
Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
However, you really probably just want to use array_sum() directly.
For reference, see:
http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
http://php.net/manual/en/function.array-sum.php
Try this. It will create a function that has a reference to your array. When you change the array you can call the product of the function, and it will recalculate the sum.
$array = ['English' => '12', 'Swedish' => '12'];
function arraySumCb(&$subject) {
return function () use (&$subject) {
return array_sum($subject);
};
}
$sum = arraySumCb($array);
echo $sum(); // 24
$array['Swedish'] = '15';
echo $sum(); // 27
$array['Swedish'] = '10';
echo $sum(); // 22
Edit: This is how I would do it.
$array = ['English' => '12', 'Swedish' => '12'];
class SumMarks {
private $_subject;
public function __construct(array &$subject = []) {
$this->_subject = &$subject;
}
public function __toString() {
return "" . array_sum($this->_subject);
}
}
$sum = new SumMarks($array);
echo $sum; // 24
$array['Swedish'] = '10';
echo $sum; // 22
Edit: Proper use of PHP anonymous functions
I dont understand your question, please ask with specific question. .
But maybe this what are you want :
function sum_marks($sub){
$result = array_sum($sub);
retrun $result;
}

php notice (trying to get property of non-object) error

So, I have following php for wp:
$usersNames = array();
foreach ($userIDs as $userId) {
$userInfo = get_userdata($userId);
$usersNames[] = $userInfo->display_name; //this one
}
I am getting an error for $usersNames.
"PHP Notice: Trying to get property of non-object in /functions.php on line"
What is going on?
Any suggestions?
Thanks
EDIT:
So, for $userIDs, I have an array of user ids. Then I am trying to get user display name etc for individual ids.
Your function get_userdata() will return False on failure, WP_User object on success.
And error Trying to get property of non-object means that this function has returned false.
Simply check if $userInfo is not empty
$userInfo = get_userdata($userId);
if (!empty($userInfo)) {
$usersNames[] = $userInfo->display_name;
}
you need judge whether $userInfo return the right obj
$usersNames = array();
foreach ($userIDs as $userId) {
$userInfo = get_userdata($userId);
$usersNames[] = isset($userInfo->display_name)?$userInfo->display_name:''; //this one
}

Codeigniter passing objects within views

I am loading a view from a Controller file and that View loads another view which a final one as below,
First view Call :
Controller: device.php
public function device_name(){
$data = new stdClass;
$data->device_name = "Apple";
$this->load->view('apple_device',$data);
}
Second view call :
View: In apple_device.php
$device_name->count = 123;
$this->load->view('device_counts',$device_name);
I am using object here instead of an array as a passing variable between views. But if i use array, it works fine.
And the above code throwing error as like below,
Message: Attempt to assign property of non-object
Any help would be appreciated.
Yes, you may still pass through objects, but not at the 'first level', you'll need to wrap the object you want to pass through inside an array.
public function device_name(){
$mobiles = new stdClass;
$mobiles->device_name = "Apple";
$data = array( "mobiles" => $mobiles );
$this->load->view('apple_device',$data);
}
This is because when CodeIgniter will initialize the view, it will check the contents of the second view() parameter. If it's an object - it'll cast it to an array via get_object_vars() (See github link)
protected function _ci_object_to_array($object)
{
return is_object($object) ? get_object_vars($object) : $object;
}
Which will in turn, turn your initial $data into:
$data = new stdClass;
$data->device_name = "Apple";
$example = get_object_vars( $data );
print_r( $example );
Array ( [device_name] => Apple )
Thus to avoid this, nest your object inside an array() which will avoid being converted.

function returns array return null

i got a php function in Wordpress that get serialized user meta : like this
function get_allowwed_tournees_ids(){
$tournees = get_user_meta($this->ID, 'tournees',true);
$tournees = unserialize($tournees);
$tournees_ids = array();
foreach ($tournees as $key => $value) {
array_push($tournees_ids, $key);
}
var_dump($tournees_ids);
return $tournee_ids;
}
get_allowwed_tournees_ids() is in a class that extends WP_User
and when i want to call it :
$id_tournees = $current_user->get_allowwed_tournees_ids();
var_dump($id_tournees);
the var_dump inside the function returns me the unserialised array, and the second var_dump outside the function returns null.
Any idea ?? Thanks !
Because you are returning $tournee_ids which is never defined. I think you should
return $tournees_ids;

Print array from class php

I'm trying to print data from an array. The array is from a class. I'm getting
array(0) { }
instead of:
Array ( [0] => header_index.php [1] => footer.php )
The code is:
<?php
class TemplateModel {
public function getTemplate($template = "index"){
switch($template){
case "index":
$templateconfig = array("header_index.php","footer.php");
break;
}
return $templateconfig;
}
}
$temodel = new TemplateModel();
var_dump(get_object_vars($temodel));
$temodel -> getTemplate();
?>
What i'm doing wrong? Thanks in Advance
var_dump(get_object_vars($temodel));
will output class member $temodel. There are no class member variables, so output is empty. If you want to output your array, you have to for example do this:
print_r($temodel -> getTemplate());
My immediate thoughts are it looks like you are setting the variables in the function 'getTemplate' and that is not being called until after the var_dump.
ADD:
And I just noticed you are not capturing the return of the function. You are var_dumping the object created from the class.
FIX:
<?php
class TemplateModel {
public function getTemplate($template = "index"){
switch($template){
case "index":
$templateconfig = array("header_index.php","footer.php");
break;
}
return $templateconfig;
}
}
$temodel = new TemplateModel();
$returned_var = $temodel -> getTemplate();
var_dump($returned_var);
?>
If you want to set the array as a variable of the object, that is a different problem.
It looks like you're not initializing the $templateconfig variable until getTemplate() is called. And you don't call it until after var_dump().
So basically, you're dumping an object that has no initalized member properties which is why you see an empty array.
Your object itself has no variables (properties) to be returned with a call to get_object_vars(). The $templateconfig variable only exists within the scope of the getTemplate() function and is not a property of the object.
If your intent is to make it a property of the object, you should do something like this:
class TemplateModel {
private $template_config = array(
'index' => array("header_index.php","footer.php"),
// add other configs here
);
public function getTemplate($template = "index"){
if(empty($template)) {
throw new Exception('No value specified for $template');
} else if (!isset($this->template_config[$template])) {
throw new Exception('Invalid value specified for $template');
}
return $this->template_config[$template];
}
}
$temodel = new TemplateModel();
var_dump($temodel->getTemplate());
Note here if you call get_object_vars() you still would get an empty array as I have made the $template_config variable private, forcing the caller to use the getTemplate() method to access the template data.

Categories