blob: 2fc5bad5215387162e284305e895a35ff9cdd329 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
<?php
// A simple PHP script
namespace App;
use Exception;
class User {
private $name;
private $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
public function getName() {
return $this->name;
}
public function getEmail() {
return $this->email;
}
public function save() {
// Simulate saving to database
echo "Saving user {$this->name} to database.\n";
return true;
}
}
function processUsers($users) {
foreach ($users as $user) {
try {
if ($user->save()) {
echo "User saved successfully.\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
}
}
// Data array
$users_data = [
['name' => 'Alice', 'email' => 'alice@example.com'],
['name' => 'Bob', 'email' => 'bob@example.com'],
];
$user_objects = [];
// Loop and create objects
if (!empty($users_data)) {
foreach ($users_data as $data) {
$user_objects[] = new User($data['name'], $data['email']);
}
}
// Call function
processUsers($user_objects);
// Alternative syntax for control structures
$count = 0;
while ($count < 3):
echo "Count is $count\n";
$count++;
endwhile;
echo "Script completed.\n";
?>
|