objects and strings - php

I was trying to return a set of objects.
But this code gives me the following error:
Catchable fatal error: Object of class User could not be converted to string in ...
public function fetchObject($psClassname ="",$paParams =array()){
$lrResource = $this->mrQueryResource;
$liResult = null;
while($row = mysql_fetch_object($lrResource,$psClassname,$paParams)){
$liResult .= $row; <-this line produces the error
}
return $liResult;
}

In your code $row is a an object (you've used mysql_fetch_object), and the .= operator tries to build a string, concatenating $liResult and $row. I believe this behaviour only works if your object implements a toString method
You could return an array of rows using this code:
public function fetchObject($psClassname ="",$paParams =array()){
$lrResource = $this->mrQueryResource;
$liResult = array();
while($row = mysql_fetch_object($lrResource,$psClassname,$paParams)){
$liResult[] = $row;
}
return $liResult;
}

That's because you are trying to convert $row to a string (the .= assumes a string is given on the right hand side)

Related

How to resolve Fatal error: Uncaught TypeError: Return value?

I have a very annoying problem to solve. I have a method that searches for a code of a sale, it is:
public function findByCode(string $code, string $columns = "*"): ?Sales
{
$find = $this->find("code = :code", "code={$code}", $columns);
return $find->fetch(true);
}
When I try to call him that:
$sales = (new Sales())->findByCode(client()->code);
It shows me the following error:
Uncaught TypeError: Return value of Source\Models\Sales::findByCode() must be an instance of Source\Models\Sales or null, array returned in
How to solve this?
You are making the findByCode function restrict to return data with type Sales and when you are using return $find->fetch(true); it will return some array of that's type is not compatible with Sales so PHP is complaining here about that. so just make a new object of Sales and return it.
The code should be some thing like this:
public function findByCode(string $code, string $columns = "*"): ?Sales
{
$find = $this->find("code = :code", "code={$code}", $columns);
$result = $find->fetch(true);
return new Sales($result);
}
So the Sales class can get the data and assign them to its properties and act as a DTO or something.

PHP cascading (passing) subsequent returns through 3 functions

I have been through S/O and have not found this specific problem although my inexperience may mean I've searched by the wrong terms. Any help would be appreciated. Thank you.
Basically, I have three PHP functions (within a class named KeyPositions). The first is called by passing an argument; the second function is called by the first and then produces an array that is passed on to the third function. By using echo and print_r I can see that everything is in place as it is being passed. The problem is occurring on the return from the final function (the 3rd). While my foreach/echo test (just before the return) shows every element in the array is present, that is not what I'm getting once I look at what is returned to the original call. Here are the steps:
Originating call: $keypositions = KeyPositions::getKPSponsor($session_userid);
Second return (where the problem starts?): return self::getKPList($sponsor_list);
Third function: public static function getKPList($arr)
Test before return (shows array contents perfectly): foreach($kppositions as $s) { echo $s['kp_root'],"<br>"; }
Return statement: return $kppositions;
But when I go back to the original function call and run this test I only receive a subset of what I would've expected from the return (above): foreach($keypositions as $t) { echo $t['id'],"<br>"; }
Is there something that I'm missing when an array is passed from one function to the next? All arrays are associative. I intentionally did not include the lengthy code within each of the functions because the functions themselves seem to be performing perfectly based on the test I do just before each return (meaning what I expect to be inside the array is fully intact at each step). I believe this may have something to do with the passing of returns from one function to the next? Any direction here would be appreciated. Thank you.
Okay. Sorry. My thought was to not muddy things with all the code. Here it is. Keep in mind, this is for testing and not for final (e.g., no PHP injection work yet.)
public static function getKPSponsor($userid)
{
return self::getKPSponsors('positions.jobholder_uid = "' .$userid. '"');
}
public static function getKPSponsors($criteria = '')
{
$sponsor_levels = array();
$sponsor_list = array();
$criteria = " WHERE $criteria";
$db = Database::getInstance();
$mysqli = $db->getConnection();
$sql_query_sponsors = "SELECT positions.position_id AS id, jobholder_uid AS uid FROM positions $criteria";
$result_sponsors = $mysqli->query($sql_query_sponsors);
while ($sponsor_level = mysqli_fetch_assoc($result_sponsors)){
$sponsor_id = $sponsor_level['uid'];
$sponsor_level['items'] = self::getKPSponsors('positions.positionmgr_uid = "' .$sponsor_id. '"');
$sponsor_levels[] = $sponsor_level;
}
foreach($sponsor_levels as $r) {
$sponsor_list[] = $r['id'];
}
mysqli_free_result($result_sponsors);
unset($r);
return self::getKPList($sponsor_list);
}
public static function getKPList($arr)
{
$kppositions = array();
$db = Database::getInstance();
$mysqli = $db->getConnection();
$sql_query_keypositions = "SELECT key_positions.kp_id AS id, key_positions.kp_root, key_positions.kp_area, key_positions.c_ksa, key_positions.c_relationship, key_positions.c_rare, key_positions.urgency, positions.jobholder_uid, master.last_name, CONCAT(master.first_name,' ',master.last_name) AS full_name FROM key_positions INNER JOIN positions ON positions.position_id = key_positions.kp_sponsor INNER JOIN master ON positions.jobholder_uid = master.email_address WHERE key_positions.kp_sponsor IN (" . implode(",", $arr) . ");";
$result = $mysqli->query($sql_query_keypositions);
while ($kp3 = mysqli_fetch_assoc($result)) {
$kppositions[] = $kp3;
}
foreach($kppositions as $s) { // My testing ...
echo $s['kp_root'],"<br>";
}
mysqli_free_result($result);
return $kppositions;
}
In case this helps further, the output from my test BEFORE the return yields:
1000014
1000015
1000016
1000012
1000006
1000022
1000017
1000018
1000019
1000020
1000021
1000008
1000009
1000010
1000011
1000004
1000005
1000007
1000013
1000003
1000001
1000002
The output AFTER the return yields:
1000001
1000002

Php class property get and set

I have the following codes.
<?php
class Reg {
private $pros = array();
public function __set($key,$val) {
$this->pros($key)= $val;
}
public function __get($key) {
return $this->pros($key);
}
}
$reg= new Reg;
$reg->tst="tst";
echo $reg->tst;
?>
But when executing this script I got the error following.
Fatal error : can't use method return value in write context in line 5
I believe that to add an element to array is possible like the above.
$array = array();
$array('key')='value';
Please make clear that I was wrong.
Thanks
The is because of you are trying to set a functions return value. $this->pros($key) means calling pros($key) function. Not setting a value to $pros array.
The syntax is wrong. Setting values to array be -
$array['index'] = 'value';
Change
$this->pros($key)= $val; -> $this->pros[$key]= $val;
and
return $this->pros[$key];
Working code
$this->pros[$key] = $value;
OR
$keys = array($key);
$this->pros = array_fill_keys($keys,$value);
The array_fill_keys() function fills an array with values, specifying keys.
Syntax:
array_fill_keys(keys,value);

php function with optional parameters using stdClass

Suppose, I have a function such as: [$data is a stdClass()]
function test_1{
...
...
if (somecondition){
$data->name = NULL;
test_2($data->name);
}
else{
$data->name = 'hello';
test_2($data->name);
}
...
...
}
function test_2($data){
if (!empty($data->name)){
test_3($data->name);
}
else{
test_3();
}
}
function test_3($s = ''){
if (!empty($s)){
//do something
}
else{
$s .= 'World';
}
}
test_3 is the function with optional parameters.
However, I get an error: Object of class stdClass could not be converted to string
I'm assuming you called your function in a manner of the form:
$data = new stdClass();
test_3($data);
This fails then as you end up in your else statement, and you can't concatenate a stdClass() to a string (in this case 'World').
A bit more review suggests that your actual function call is test_3($data->name), and $data->name is likely of stdClass() instead of a string that can be concatenated with 'World'.
For reference, if you have an error, it'd be helpful to provide the actual line number the error is corresponding to . . . I'm guessing the error is due to the concat, since that's the only place where I see a stdClass() to string conversion would be necessary.

Static method, Zend_View error

I have a static method 'findAll' on a model which basically gets all rows with certain criteria. This method works fine and I can call it using:
$m::findAll();
Where $m is the model name as a variable. I can output this and it returns correct results. However, when assigning this to a variable in the Zend_View object, as:
$this->view->viewvariable = $m::findAll();
I get the error:
Zend_Db_Table_Exception: Too many
columns for the primary key
Any ideas why?
Find all function:
final public static function findAll($where = false, array $options = array()) {
$object = new static();
if (!empty($options)) $options = array_merge($object->options, $options);
else $options = $object->options;
$run = $object->buildDefaultSelect($where, $options);
$rows = $run->fetchAll();
if ($options['asObject'] == true) {
$result = array();
foreach ($rows as $r) {
$class = new static();
$class->setInfo($r);
$result[] = $class;
}
return $result;
} else {
if (count($rows) > 0) return $rows;
else return array();
}
}
Note: This function works fine everywhere apart from when assigning to a view variable. If I run the below (not assigning it to a view variable), it shows the correct array data.
var_dump($m::findAll($module['where'], $module['options']));
exit;
In my view (I have replaced the actual name with viewvariable for the sake of this post):
<?php foreach($this->viewvariable as $item) { ?>
//Do some echoing of data in $item
//Close foreach
I doubt the issue is with Zend_View. It's hard to tell without seeing your code, but my guess is that findAll() is using the Zend_Table_Db find() function incorrectly.
To my knowledge, the only place that throws that exception is the find() function on Zend_Db_Table_Abstract.
Perhaps, inside the findAll() function (or in a function it calls) you're doing one of these:
$zendDbTable->find(1,2) //is looking for a compound key
$zendDbTable->find(array(1,2)) //is looking for two rows
When you really want the opposite.

Categories