php and sql together in the func of a class - php

this piece of code was given in a book.
$query="select name, description from widget where widgetid=$widgetid";
$rs=mysql_query($query,$this->connect);
if(!is_resource($rs))
throw new exception("could not execute the query");
if(!mysql_num_rows($rs))
throw new exception("found no rows");
$data=mysql_fetch_array($rs);
$this->name=data['name'];
$this->description['description'];
what is meant by the last two lines of the code?

The third line before the end :
$data=mysql_fetch_array($rs);
will fetch one row of the resultset that corresponds to the SQL query, and assign it, as an array, to $data.
See the documentation of mysql_fetch_array() for more details.
The next line :
$this->name=data['name'];
is not valid PHP, and will result in a Parse Error.
Instead, to be valid, it should be written like this :
$this->name=$data['name'];
Note the additionnal $, that means that $data is a variable.
It will assign the value of the name item of the $data array to the name attribute of the current object.
Basically : the name attribute of the current instance of your class will contain the value of the name column of the row you've fetched from database.
And, finally, the last line :
$this->description['description'];
doesn't do anything : you access the description item of the attribute description of the current object -- that attribute being an array ; but you don't do anything with it.
I suppose it should be written :
$this->description = $data['description'];
In which case it would do the same kind of thing as the previous line -- with the description item/field/attribute.
Considering your question, you should take a look at the PHP manual, and, especially, at the following sections :
Arrays
Objects
Classes and objects

$this refers to the current instance of the class.
-> tells PHP to refer to a member of the instance.
name is the referred member.
So, the following line:
$this->name = $data['name'];
Sets the property name of the current instance ($this) to whatever value held by the array $data at index name.
For more information, you can read the OOP Basics in the PHP Documentation:
PHP Documentation: Classes and Objects - The Basics
PHP Documentation: Classes and Objects - Properties

Well for starters, "data" is the array that hold the results of your query.
In your query you are retrieving "name" and "description" from the table "widget".
$this->name = data['name'] is assigning the value of name from the query to the name property or variable in your instance. $this refers to the current instance
Does that help?

Considering this code is from book, I think it is part of some method where widget name and description is fetched from DB and updated on class properties.
BTW, if last two lines are as is as you pasted then there is some print mistake :)

Related

Calling a variable by passing variable name as a string

I've got a list of variables. Let's call it a=1,b=2,c=3. I would like to pass the variable name to a function as a string and then retrieve its' value. Is there a way to achieve this in PHP? I', hoping to use this in page object pattern with Gherkin to pass a variable name to a gherkin step.
I was able to resolve the problem by using ${$arg} notation as described by #waterloomatt above.

Serialized object coming out with internal value references

This is by far the strangest thing i have seen in PHP, but there surely is some sort of explanation.
Using serialize() i am storing some objects. At a later point, i revive them using unserialize().
Today i discovered a problem with an object that has been unserialized. Picture this scenario:
object__product_bundle Object (
[collateralValue] =>
[collateralGroup] =>
)
Now imagine $obj to be an instance of object__product_bundle as shown above.
When i did:
$obj->collateralValue = 10;
And checked the object variables, i was shown:
object__product_bundle Object (
[collateralValue] => 10
[collateralGroup] => 10
)
Mindboggling!
I spent an hour smashing my head against the table, as this didn't make sense. But when i started using var_dump() on the object, before making changes to it, i saw this:
object(object__product_bundle)#28 (15) {
["collateralValue"] => &NULL
["collateralGroup"] => &NULL
}
Apparently these properties/variables were somehow linked. I researched &NULL and all i found was this question which told me i am dealing with some sort of references.
But how?
My object comes from a serialized string.
Now, taking a look at the serialized string i found this:
s:15:"collateralValue";N;s:15:"collateralGroup";R:15;
What is R:15 ?
Can it be the issue?
How can this problem be addressed and where does it come from?
EDIT
After digging deeper, i found the culprit.
Orientiation:
The objects (as described above) are stored into a property of another object, which is the item of a shop cart.
class shopCart {
public $storage;
}
$cart->storage[] = new shopCart_item();
class shopCart_item {
public $object;
}
$object is where the products (object__product_*) are stored.
Upon placing an order, with the aim of being repeated (subscription), this entire shopCart is stored into the database as a blob.
Whenever a subscription order is scheduled, an automated task then grabs the old shopCart and generates a new order from it.
And here i found the culprit - i added the properties (collateralValue etc.) later during development, but there had already been stored orders.
Now during debugging i found that this is where PHP starts creating references, although i do not understand why.
Simply put:
static public function generateOrderFromSubscription() {
[...]
$order = new object__webShop_order();
var_dump($subscription->cart); // <-- no references are in here at all
$order->cart = serialize($subscription->cart);
var_dump($order->cart); // <-- suddenly, here i have the references
}
Apparantely, i use __sleep() for each object__product_* - which returns those variable names (including collateralValue and so on).
The question now becomes then: Why does PHP create references, when it is dealing with new properties for objects that were asleep but whose structure has changed in the meantime?
Very confusing!
EDIT #2
Finally some hope.
My __sleep() function basically returned a hardcoded array of variable names, as there were a ton of others i never wanted to store in the database. This approach apparently led to the current problem described in this question.
I still do not know why PHP creates references for variables in objects that were awoken without having those variables at all, but with those variables being returned in __sleep().
The only sensible solution to me, seemed to be to adapt __sleep(). I now do this:
public function __sleep(){
$vars=array(
'dbId',
'title',
'articleId',
'price_per_unit',
);
if(isset($this->collateralValue))
$vars[]='collateralValue';
if(isset($this->collateralGroup))
$vars[]='collateralGroup';
}
This way, __sleep() will not return (any of those two new) variable names (collateralValue, collateralGroup) which are not in use in the current object.
Well let's analyse your serialized string:
s:15:"collateralValue";N;s:15:"collateralGroup";R:15;
First property (key):
s:15:"collateralValue"
s just means it is a string
15 is the size of the string
collateralValue is the string itself the value (And if you look the string is 15 characters long)
First property (value):
N
N just mean NULL
Second property (key):
s:15:"collateralGroup"
s just means it is a string
15 is the size of the string
collateralGroup is the string itself the value (And if you look the string is 15 characters long)
Second property (value):
R:15
R means reference
15 means to the 15 value. So here the 15 value is probably the property collateralValue, which means if you change the value of it it also changes the value of the collateralGroup property
For more information see: http://www.phpinternalsbook.com/classes_objects/serialization.html

Undefined property, even though it's there

I have an object, Brand, and I want to print the id of this object.
I am getting the following error when doing return Sentry::getUser()->brand()->get()->id:
Undefined property: Illuminate\Database\Eloquent\Collection::$id
However, if I remove the ->id part, I am getting the whole object just fine, including the id (return Sentry::getUser()->brand()->get())
What am I doing wrong?
You need to use:
return Sentry::getUser()->brand()->first()->id;
Otherwise, you end up with a collection of users (even though that collection may only contain one user).
it might be reserved in a framework you used. My guess s that every object of any kind is a default object-type object that has an id of its own. If possible change the "id" to brand_id or something like that.
If there is only one object and will always be one, you can use return Sentry::getUser()->brand()->first()->id. That retrieves a single object, while get () returns an array of objects even if there is only one match.

How can I use a reference only and make no copies of the object argument in php

I have a function that requires information to be passed to it. The information is contained within an object. Therefore I must pass that object as one of the function arguments. The object is very large however, and I would like to reduce the overhead involved in making copies every time it is passed. Here is an example of
My function Call:
1 myFunction($myObject1);
and the function:
2 function myFunction($myObject2){
3 //do stuff
4 }
I understand there is more to it in php than just pass-by-reference vs pass-by-value. Correct me if I am wrong, but I believe on line 1 there is only a reference to the object made, but on line 2 the object is copied. To avoid this copy I have replaced ($myObject2) with (&$myObject2). I still refer to the object within the function definition as $myObject2 and everything seems to work. I believe I am now using a reference only and therefore making no copies of the object (which was my goal). Is my thinking correct? If not not why?
In PHP5, "objects" are not values. The value of the variables $myObject1, $myObject2 are object references (i.e. pointers to objects). You cannot get "the object itself"; objects can only be manipulated through these pointers.
Assignment and passing by value only copy values. Since objects are not values, they cannot ever be cloned through assignment, passing, etc. The only way to duplicate an object is to use the clone operator.
Putting & on a variable makes it pass or assign by reference, instead of by value without the &. Passing by reference allows you to modify the variable passed. Since the value of a variable cannot be an object, this has nothing to do with objects.

Illegal string offset when using string to reference array

I have classes, each with a date related member variable that always has the same naming format - field_{$node->type}_date
For example, if I my node type was 'car', the date field would be named field_car_date
So I am looping over all my nodes and I want to access the date related field for each of them. However I am getting an error. Here's the code
$date_field_key = 'field_' . $node->type . '_date';
if (isset($node->$date_field_key['und'][0]['value'])) {
I get an error because of the second line. The error is - Illegal string offset 'und'
The date related variable is an array and it does have an element with the key 'und'. If I write out the line explicitly - $node->field_car_date['und'][0]['value'] - it works fine. It's just when I dynamically create the field name that I get this problem.
Any solution for this, is my syntax incorrect?
You need to surround you key value in {} because it's a dynamically-assigned variable.
In your second line, you have $node->$date_field_key['und'][0]['value'] where you should have:
$node->{$date_field_key}['und'][0]['value']
Notice the {} surrounding the date_field_key
Good luck!
There is no reason to spare the variable:
$array = $this->$date_field_key;
$value = $array['und'][0]['value'];
If you get it to work, we then can discuss more advanced topics.

Categories