Jump to content

An object array in PHP


Recommended Posts

I have my object called Product, that has a simple set() function.  I want to create an array of type Product called myProducts.  How can I do this?  In C++ I would use Product myProducts[50], but this doesn't work in PHP and I have had a look on some website but I can't get a satisfactory answer (or one that works).  Can someone explain why?

 

//In C++ I would do it in the following way:
Product myProducts[10];
myProducts.set(1,2,3,4);

I just want to do this in PHP, why is it so hard??

Link to comment
https://forums.phpfreaks.com/topic/103888-an-object-array-in-php/
Share on other sites

Correct, they do not need a size definition. PHP is different from C++ in that aspect.

 

Another note, there is no different between arrays and hashes and in PHP. So you can actually do this too:

 

<?php
  $products = array();
  $products[] = new Product();
  $products['foobar'] = new Product();
  $products['some_key'] = new Product();
  $products[] = new Product();
?>

Thats a pretty good idea.  Thanks for your help in this.  I'd sooner code this in Java using JSP but the server only supports PHP.  I have yet another problem.  I have a function called getProducts() that returns an array of type Product from a SQL database.  I'm having trouble calling the function.  My code so far:

$table = array();
$table[] = new Product();  //create a new Product array
$table[] = getProducts($query);  //call the get products function
echo($table[1]->get());  //call the get function on the first product in the array

 

The problem is with the last line.  I just get the following error:

Fatal error: Call to a member function get() on a non-object in C:\xampp\htdocs\range.php on line 25

 

Any ideas?  Are you a professional PHP developer?

The following line is what initiates the array

$table = array();

The next line is not needed. I used it as an example because you said you had an "object called Product", and that is the syntax to initiate an object of type "Product".

$table[] = new Product();  //create a new Product array

 

So, that being said, the above lines aren't even needed :) If the function is returning an array, you simple store it's return value into a variable. No need to declare the variable ahead of time. So the revised code would be:

<?php
$products = getProducts($query);  //call the get products function
//Now we have a numeric array in $products
//Just like in most other languages, the array starts with an index of 0
echo $products[0]->get();  //call the get [s]function[/s] method on the first product in the array
//I also removed the outer parenthesis as they are not needed for echo

//If you want to loop over all the products, it would look something like this:
foreach($products as $product){
  echo $product->get();
}
?>

 

PHP has some pretty significant differences from C++ and Java. Here is a good site I always recommend to PHP noobs, I would give it a read:

http://devzone.zend.com/node/view/id/627

Thanks for your help on this.  Just a couple more things.  I tried the code you said and the for loop works, but the individual statement does not:

 

$products = getProducts($query);
foreach($products as $product){  //this works fine
  echo $product->get();
}

echo $products[0]->get();  //this line does not work, I get the same error.

 

Additionally, I have another issue not related to the one above but one that you might be able to quickly solve for me.  I am trying to output some JavaScript code in my PHP, but it doesn't work.  The JavaScript code below works fine in normal HTML, but not in PHP and I can't figure out why.  The synax seems to be ok.

 

echo('<script>function clear() {window.alert("test")}</script>');
echo('<a href="#" onclick="clear()">Delete a product</a>');

 

That PHP tutorial you send is pretty good.

Hum, I need to know more about that functions return value then. What does the output from this look like:

<?php
  $products = getProducts($query);
  print_r($products);
?>

 

As for the javascript, it's a weird issue, and is javascript related (not PHP). I can't give you a reason why, but clear() doesn't work inside the onclick. But, click2 does:

<?php
echo('<script>function clear2() {alert("test");}</script>');
echo('<a href="#" onclick="clear2();">Delete a product</a>');
?>

gotta love technology....

That is weird about the JavaScript.  clear in JavaScript must be some form of keyword.  I should have spotted it.  Why does coding have to be so ahrd sometimes?  And its always the little things like missing semi-colon.  :-\

 

Anyway,  the output from your command is:

 

Array( => Product Object ( [id:private] => [name:private] => [range:private] => [desc:private] => [more:private] => [price:private] => ) )

The function getProducts() is actually called from a class, but this has no real functionality yet.  Therefore in the last example you said I simply put $myClass-> in front of the getProducts() function.  The code for the getProducts() function:

 


public function getProducts($qry)  //Selects all the data in the database so someone can view
{
	$link = $this->connect(); //Connect to the database

	$result = mysql_query($qry,$link);  //get the PHP records

	//Test if the query is valid and throw exception if failed
	if (!$result) {
		throw new Exception(mysql_error($link),QUERY_FAILED);
	}
	else if (mysql_num_rows($result) == 0 ) {
		//throw new Exception("There are no results for your query",NO_RESULTS);  //Through exception if there are no results
		echo('No results');
	}

	$i = 0;


	$products = array();

	//Populate an array of products
	while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

			$products[i] = new Product();
			$products[i]->set($row['prodId'], $row['prodName'], $row['prodRange'],$row['prodDesc'],$row['prodMore'],$row['prodPrice']);
			$i = i + 1;
	}

	mysql_close($link);  //Close the link

	return $products;  //return the table
}

The connect() function is call to a small protected function within the class to connect to the MySQL database.  Hope thats everything you need.

You are missing $ sings on these rows (should be $i):

				$products[i] = new Product();
			$products[i]->set($row['prodId'], $row['prodName'], $row['prodRange'],$row['prodDesc'],$row['prodMore'],$row['prodPrice']);

 

the better way to do it is this though (get rid of the $i all together):

	while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
			$product = new Product();
			$product->set($row['prodId'], $row['prodName'], $row['prodRange'],$row['prodDesc'],$row['prodMore'],$row['prodPrice']);
			$products[] = $product;
	}

Its always one character thats missing.  So frustrating when programming!!!  Well that works now but I've hit yet another problem (hopefully the final one).  I'm still using $i because I prefer it that way, but thanks for the tip.  The information does not seem to be being passed to the class function.  When calling

 

$products[$i]->set($row['prodId'], $row['prodName'], $row['prodRange'],$row['prodDesc'],$row['prodMore']);

Nothing happens.  If I echo one of the variables e.g. echo $row['prodName'];  I get a value that can be seen without a problem.  My set function code within the class:

	public function set($pId,$pName,$pRange,$pDesc,$pMore)
	{
	$id = $pId;
	$name = $pName;
	$range = $pRange;
	$desc = $pDesc;
	$more = $pMore;
	echo($name);
	}

 

When I echo $name, nothing appears in the browser, yet data is quite clearly being passed to it because I can see that data just as it comes out of the database.  What am I missing?

um...not completely sure what you mean. but the set function should be:

 

<?php
	public function set($pId,$pName,$pRange,$pDesc,$pMore)
	{
	$this->id = $pId;
	$this->name = $pName;
	$this->range = $pRange;
	$this->desc = $pDesc;
	$this->more = $pMore;
	echo($this->name);
	}
?>

 

to read/write values inside a class, you need to use $this->var_name (which you did properly in getProducts)

That works fine now, it was the $this keyword that did it.  Although now I'm having a similar problem.  Copied from the same function as before, but instead of an array of Product objects, its just simply an array.  See the code.

 

		$table = array();  //create array

	//Populate the array
	while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

			$table[$i] = $row['rangeName'];
			$i = $i + 1;
			echo $row['rangeName'];  //this echos fine
                                                   echo $table[$i];  //this echos fine
	}

	mysql_close($link);  //Close the link
	echo $table[0];  //this does not echo at all, yet when the number is changed to 1 it does, how strange
	return $table;  //return the table
}

 

Any ideas on that one?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.