Jump to content

[SOLVED] Returning array in class


peuge

Recommended Posts

Hey all,

 

I have a class, and some of the methods are going to need to return arrays, eg. Query a database and return an array of names. So to begin I tried something really simple just to see how this would work (I am new to OOP)

 

//in another php page
$amnt = new test_class;
$arr = $amnt->test_array();
for ($i=1;$i<10;$i++){
  echo $arr[$i];
}

//in the class
var $arr = array();
function test_array(){
  while ($this-> i != 10){
        $this->$arr[$this->i]= $this->i; //This is line 40
$this->i++;
  }
  return $this->arr;	
}

 

from This i get this error

Fatal error: Cannot access empty property in C:\xampp\htdocs\zaart\gal_class.php on line 40

 

Can anyone please help me, much appreciated

Link to comment
https://forums.phpfreaks.com/topic/144461-solved-returning-array-in-class/
Share on other sites

<?php

class file_handle{
  var $name;
private $dir_images = "images/";
private $dir_big = "big/";
var $i=0;
var $first_pic_title;
var $arr = array();

//function __construct($names){
//	$this->name = $names;
//}

function amount_pics(){
	if ($handle = opendir($this->dir_images)) {
    	while (false !== ($file = readdir($handle))) {
      	if ($file != "." && $file != ".." && $file != rtrim($this->dir_big,"/")) {
			  $this->i++; // = $this->i + 1;								
       	}
   		}
    closedir($handle);
	} 
	else{ 
		$this->i = 0;
	}
	return $this->i;
}

function get_first_pic($artist,$cat){
	$sql = "SELECT * FROM pictures WHERE artist = '$artist' AND cat = '$cat'";
	$result = mysql_query($sql);
	$row=mysql_fetch_array($result); 
	$this->first_pic_title = $row["title"];
	return $this->first_pic_title;
}

function test_array(){
  while ($this-> i != 10){
		$this->$arr[$this->i]= $this->i;
		$this->i++;
	}
	return $this->arr;

}


}

 

Sorry bout the indentation, this editor doesnt take it exactly how I have it.

 

 

For testing purposes I would replace this....

 

function test_array(){
  while ($this-> i != 10){
		$this->$arr[$this->i]= $this->i;
		$this->i++;
	}
	return $this->arr;

}

 

with....

 

function test_array() {
  for (range(0,10) as $count) {
    $this->$arr[$count] = $count;
  }
  return $this->arr;
}

 

ps: Your also using the older php4 class syntax.

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.