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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.