Pass an object attribute by reference - php

I have this php function to add an object to the database, but it is giving me some troubles to make it work. I'm pretty used to the java way, so i tried to follow the same pattern, and I'm getting an error message that says "Strict standards: Only variables should be passed by reference".
This is the code:
public function saveUser(User $user){
$this->connection = DaoFactory::openConnection();
$this->query = $this->connection->prepare($this->SAVE_QUERY);
$this->query->bindParam(':name', $user->getName());
$this->query->bindParam(':lastName', $user->getLastName());
$this->query->bindParam(':age', $user->getAge());
$this->query->bindParam('gender', $user->getGender());
$this->query->bindParam(':email', $user->getEmail());
$this->query->bindParam(':password', $user->getPassword());
$this->query->execute();
$this->connection = null;
}
I've searched and i found that the object attribute should be placed in a variable to avoid this issue, but by doing so, the code gets very messy and complex.Example:
$name = $user->getName();
$this->query->bindParam(':name',$name);
Is there any other way to solve this?

bindParam expects a variable passed by reference, you're instead giving it a value returned from a function, which cannot be passed by reference. So instead, use the other API method bindValue() to bind your values.
See https://stackoverflow.com/a/14413428/476 for what the difference is.

Related

Dynamically load value from $_POST or $_GET the short way

I'm writing a form-helper class in php, that should check if a value is submitted via the method, the form defined.
public function getValue($name) {
$getFrom = ($this->method == 'post') ? '_POST' : '_GET';
return isset($$getFrom[$name]) ? $$getFrom[$name] : null;
}
$this->method is post or get, it's form-dependent.
This method looks fine for me, but php throws a "Illegal string offset" warning. What can I do without using an if-block.
Thank you!
I know that the replies have been an attempt to help the user with a better approach, but they do not answer the question. Why is it throwing the error that he sees? I just tested this to ensure I was correct in my assumption.
When he uses $$getFrom[$name], PHP first parses "$getFrom[$name]". That is what is throwing the error. He obviously wants $getFrom to be parsed without including [$name]. So, he needs to use ${$getFrom}[$name].
Try this,
public function getValue($name) {
return isset($_REQUEST[$name]) ? $_REQUEST[$name] : null;
}

Unable to pass a parameter to my function?

I have the following in a common.php file:
$debug = true;
function debug_to_screen(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
print("Debug Mode: " + $value);
}
}
}
In my main file I then call this function with the following:
require("common.php");
if(!isset($_COOKIE["qcore"]))
{
debug_to_screen("Cookie not found: ", var_dump($_COOKIE['qcore']));
}
However I'm receiving the following error:
Fatal error: Cannot pass parameter 1 by reference in
C:\DWASFiles\Sites\junglegym\VirtualDirectory0\site\wwwroot\wp-content\plugins\QCORE\login.php
on line 8
This is one of the first time's I've tried making a function that can be passed multiple values, so I don't have the skill set to understand why this isn't working. Basically - I'd like to make a debug function that I can pass multiple values to, that is defined in my common file.
Your problem is here:
debug_to_screen("Cookie not found: "...
You are passing to the function which is expecting the data to be passed by reference - meaning you are sending it the ACTUAL variable, not a copy of it.
You will need to make the array first, then pass i by reference to the function.
Something like this:
$array=$_COOKIE;
debug_to_screen($array);
In your function, you defined it as:
function debug_to_screen(&$array)
The extra & means the function is taking the ACTUAL variable, not a copy of it.
This will also not work:
function julie(&$bob)
{
// something..
}
julie(5);
This is because although the function can change the 5, it cannot be returned via the reference pass.
$var1=5;
julie($var1);
This would have worked perfectly well, as $var1 can be modified and the external code calling the function can use the changed variable.
You function function debug_to_screen(&$array) accepting only one argument and however you are sending text as first argument and cookies as second argument.
So
replace
debug_to_screen("Cookie not found: ", var_dump($_COOKIE['qcore']));
to
debug_to_screen($_COOKIE['qcore']);
There's no need to pass by reference, and you're passing two arguments when only one is defined. You're also trying to print an array, var_dump prints not returns.
I think you need to look at the PHP docs for the functions you're using, there are a number of issues here.

PHP Function name must be a string error on new variable

I am getting the error:
Function name must be a string on this code:
$profile_data = $user_data('first_name','last_name','email');
Any ideas why this could be?
While you can use variables as function-names, to do so requires the variable to be a string.
The variable $user_data sounds more like an array, or even possibly an object. If this is true, you will receive the error specified. Per the comment from #Jon, it could also be possible that user_data() is a method and the $ is a typo.
If none-of-the-above helps, please all relevant code, specifically the creation of the $user_data variable (or a var_dump($user_data) output).
in php function define following
$profileData = user_date('first_name','last_name','email');
function user_date($first_name,$last_name,$email){
}

PHP: Fatal Error Call to a member function ... on a non-object

I'm having an issue with PHP as it keeps throwing the Exception mention in the title.
It fails on the following line:
$item->getDescription();
I understand what the error should mean ($item is null). However, $item is not null.
The scenario is as follows:
This is a script that syncs products from a supplier to a store. For that purpose, I have created my own class (SimpleProduct). This class has a getDescription() function.
The problem is that the data I'm receiving tend to have a lot of garbage, like items that haven't been filled in yet. The script should skip these items and keep on iterating across the rest of the products.
This fatal error kills the entire script.
I've already tried implementind safeguards to prevent this from happening, but it still occurs constantly. Here's the current code (some snippets removed as they arent pertinent to the currect case).
//This is part of a class that performs the sync
public function syncProduct($item) {
if(empty($item)) { return "Not a product"; }
else { var_dump($item) }
$foo = $item->getDescription();
}
When checking the var_dump result, I get an object with some values filled in. Seeing as it is of the correct type (SimpleProduct) and it is not empty/null, I would suspect this error to stop occurring, but it still does.
Also note that several product syncs have already occurred without any errors before this one pops up, so I know the code is valid. Somehow, this specific case slips past my null-checks.
Is my null-check faulty?
How can an error for a non-object be thrown when the object in question does exist?
Instead of checking whether if the variable is empty, why not check whether if it's an instance of SimpleProduct?
if ($item instanceof SimpleProduct)
{
}
http://php.net/manual/en/language.operators.type.php
Surely the object is still not available in the context of the function syncProduct.
Try to do a var_dump($item) to confirm its there and execute it within the else part of the code to ensure its not empty.
To check if $item is an object You can use is_object()
Your null check is not preventing the object to be used even if it is null contains non-objects.
Use this:
public function syncProduct($item) {
var_dump($item);
if($item InstanceOf SimpleProduct) {
$foo = $item->getDescription();
}
return "Not a product";
}
I stand corrected! I didn't notice the return statement. The other case for this to occur would be if the value from $item would be non-empty but not a product either - most likely a scalar or array because using objects as other types of objects issue a different error regarding methods not being found.
I also run into a similar problem where after running this:
$user = DB::getInstance()->action($action="SELECT * ", 'users');
Then checking whether $user is an instance of DB, I found that it wasn't. I then decided separate it as follows:
$user = DB::getInstance();
$user->action($action="SELECT * ", 'users');
After doing this and using instanceof() method it shows that it is now an instance and the fatal call to member function error disappears.

PHP: call a function from another function (out of scope?)

I'm having a problem creating webservices through nuSOAP (although i believe my problem has nothing to do with it)
What i'm trying to do:
function loadActiveItems() {
$list = Item::loadActive();
$ret = array();
foreach ($list as $val){
//two tests to check if i really have an object and if the toDTO method is callable
echo var_dump($val);
echo is_callable(array($val, 'toDTO'));
array_push($ret, $val->toDTO());
}
unset($val);
return $ret;
}
I'm getting the following error:
Call to a member function toDTO() on a non-object
and both var_dump($val) and is_callable are returning the expected (the object and true, respectively) from what i've been seeing online, it appears i have a out of scope problem... but for some reason i don't seem to get my head around it :P
Thanks in advance
EDIT: well just check that apparently i don't understand is_callable either because i always get 1 as the result...
EDIT2: i'm using php-activerecord if that helps in any way
toDTO() may be undefined in your class Item.
Another reason may be that the method isn't public or as #Grep said` static.
This error never happens on an object that defines the method but it is static or protected/private:
Call to a member function toDTO() on a non-object
That error only happens if $val is not an object. Usually a NULL, FALSE or other scalar.
It's usually a FALSE when the object came for a db_fetch() function but the fetch or the query before it failed.
It's usually a NULL when you have an array that may have NULLs in it.
var_dump($list) and see what's in there and if there are any NULLs. Also change your foreach to have a $key and var_dump($key) as well to see which key is dumped last before the error is issued.
Okay so i figured out the problem... thanks for all the help!
I was calling toDTO of another object inside toDTO... problem was that object could be a null!
So a simple if(object==null) solved the problem!
Thanks again!

Categories