Jump to content

TypeCasting Array Elements into Custom Objects


yajuu

Recommended Posts

I have a class 'User' this class is contained in a seperate file 'User.inc'.  Inside the class user i have a function 'getUsers()' which returns an array of type 'User'.

class User
{
var FirstName;
var LastName;

public function setFirstName($firstName)
{
$this->FirstName = $firstName;	
}
public function getFirstName()
{
return $this->FirstName;
}
public function setLastName($lastName)
{
$this->LastName = $lastName;
}
public function getLastName()
{
return $this->LastName;
}
public function getUsers()
{
$Users;
$DBConnect = mysqli_connect('localhost', '******, '******', '******');
$QueryString = "SELECT * FROM user";
$QueryResult = mysqli_query($DBConnect, $QueryString);
$Row = mysqli_fetch_row($QueryResult);
while ($Row)
{
 	$user = new User();
	$user->setFirstName($Row['FirstName']);
	$user->setLastName($Row['LastName']);
	$Users[] = $user;
	$Row = mysqli_fetch_row($QueryResult);
}
mysqli_close($DBConnect);
return $Users;
}
}

 

In my seperate PHP page I am trying to display the list of users:

include("Classes/User.inc");
$User = new User();
$UserList = $UserClass->getUsers();
$UserCount = count($UserList);

for ($i = 0; $i <= $UserCount; $i++)
  {
             $User = (User)$UserList[$i]; 
  	echo "<h1>", $User->getFirstName()," ",  $User->getLastName(),"</h1>";
  }

 

Is this possible?

Not possible. But it would be nice, eh? :)

 

I've tried to do typecasting for custom objects before and it's not possible. The best solution for you, though, is to either write an Iterator, or.. have the User->__construct() method take a raw array and parse it.

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.