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']; 开发者_如何学Python
$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 :)
精彩评论