Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Casting Variable as Object type in foreach Loop
In PHP, you can cast variables as specific object types within foreach loops to improve IDE autocompletion and code clarity. This is particularly useful when working with arrays of objects where the IDE needs hints about the object type.
Using @var Annotation
Most IDEs like NetBeans and IntelliJ support @var annotations in comments to specify variable types −
<?php
class User {
public $name;
public $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
}
$users = [
new User("Alice", "alice@example.com"),
new User("Bob", "bob@example.com")
];
foreach ($users as $user) {
/* @var $user User */
echo $user->name . " - " . $user->email . "<br>";
}
?>
Alice - alice@example.com Bob - bob@example.com
Using @return Annotation
You can also use @return annotations in methods that return arrays of objects −
<?php
class UserRepository {
private $users = [];
public function __construct() {
$this->users = [
new User("John", "john@example.com"),
new User("Jane", "jane@example.com")
];
}
/**
* @return User[]
*/
public function getUsers() {
return $this->users;
}
}
$repository = new UserRepository();
foreach ($repository->getUsers() as $user) {
/* @var $user User */
echo "User: " . $user->name . "<br>";
}
?>
User: John User: Jane
Alternative Type Declaration
In modern PHP versions, you can use inline type hints for better code documentation −
<?php
$products = [
(object)["name" => "Laptop", "price" => 999],
(object)["name" => "Phone", "price" => 599]
];
foreach ($products as $product) {
/** @var stdClass $product */
echo $product->name . ": $" . $product->price . "<br>";
}
?>
Laptop: $999 Phone: $599
Conclusion
Using @var annotations in foreach loops helps IDEs provide better autocompletion and reduces runtime errors. This practice improves code maintainability and developer productivity when working with object arrays.
