PHP 数组提取对象
假设我有一个用户定义类的对象数组。 想知道如何在 PHP 中提取数组的元素。
// class definition
class User
{
public $fname;
public $lname;
}
// array of objects of the class defined above
$objUser1 = new User():
$objUser2 = new User():
$objUser3 = new User():
$objUser4 = new User():
$alUser = array();
$alUser[] = $objUser1;
$alUser[] = $objUser2;
$alUser[] = $objUser3;
$alUser[] = $objUser4;
// trying to iterate and extract values using typcasting - this does not work, what is the alternative.
foreach($alUser as $user)
{
$obj = (User) $user; // gives error - unexpected $user;
}
这就是我以前在 Java 中从 Java ArrayList 中提取对象时所做的事情,因此认为 PHP 的方式可能类似。 谁能解释一下。
Suppose I have an array of a objects of user defined class. Wanted to know how do I extract the elements of the array in PHP.
// class definition
class User
{
public $fname;
public $lname;
}
// array of objects of the class defined above
$objUser1 = new User():
$objUser2 = new User():
$objUser3 = new User():
$objUser4 = new User():
$alUser = array();
$alUser[] = $objUser1;
$alUser[] = $objUser2;
$alUser[] = $objUser3;
$alUser[] = $objUser4;
// trying to iterate and extract values using typcasting - this does not work, what is the alternative.
foreach($alUser as $user)
{
$obj = (User) $user; // gives error - unexpected $user;
}
Thats how I used to do in java while extracting objects from the Java ArrayList, hence thought the PHP way might be similar. Can anyone explain it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PHP 是一种动态类型语言。 大多数情况下不需要强制转换。
无法转换为用户:请参阅有关 type 的 PHP 文档杂耍和铸造。
此示例将打印“
$user is a object (User)
”四次。PHP is a dynamically typed language. There is no need to cast in most cases.
It is impossible to cast to a User: see PHP's documentation on type juggling and casting.
This example would print "
$user is a object (User)
" four times.例如,Eclipse PDT 最好能够确定代码完成的对象类型。 否则,您将陷入回溯,在哪里创建数组以及将哪些对象放入其中,然后查看类文件以查看哪些函数可用(或者临时创建一个新的 theObject() 以查看可用的方法/属性,如果您如果许多对象调用创建这些数组和其中的对象的函数,那么知道它是什么类型的对象有时可能并不那么容易,因此必须回溯以查看这些数组是如何创建的)。 听说其他一些 IDE 可能能够像 phpEd 一样更好地确定类型?
It would be nice for example Eclipse PDT to determine the type of object for Code Completion. otherwise you are stuck backtracing, where the array was created and what objects were put into it and then look at the class file to see what functions are available (or temp create a new theObject() to see what methods/properties are available if you know what type of object it is. other times may not be as easy if many objects call functions that create those arrays and objects in them, so have to backtrace to see how those arrays made). Heard a few other IDE's may be able to determine type better like phpEd possibly?
为什么需要为此进行类型转换?
Why do you need typecasting for this?