php语言代码大全
Hello World:
php<?php
echo "Hello, World!";
?>
变量和数据类型:
php<?php
$age = 25; // integer
$name = "John"; // string
$isStudent = true; // boolean
$price = 19.99; // float
// 输出变量的值
echo "Name: $name, Age: $age";
?>
数组:
php<?php
// 数字索引数组
$numbers = array(1, 2, 3, 4, 5);
// 关联数组
$person = array("name" => "John", "age" => 30, "city" => "New York");
// 访问数组元素
echo $numbers[0]; // 输出: 1
echo $person["name"]; // 输出: John
// 遍历数组
foreach ($numbers as $number) {
echo $number . " ";
}
?>
条件语句:
php<?php
$age = 25;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>
循环语句:
php<?php
// for 循环
for ($i = 0; $i < 5; $i++) {
echo $i . " ";
}
// while 循环
$i = 0;
while ($i < 5) {
echo $i . " ";
$i++;
}
// foreach 循环
$numbers = array(1, 2, 3, 4, 5);
foreach ($numbers as $number) {
echo $number . " ";
}
?>
函数:
php<?php
// 定义函数
function greet($name) {
echo "Hello, $name!";
}
// 调用函数
greet("John");
?>
类和对象:
php<?php
// 定义类
class Person {
public $name;
public $age;
// 构造函数
function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
// 方法
function greet() {
echo "Hello, my name is {$this->name} and I'm {$this->age} years old.";
}
}
// 创建对象
$person = new Person("John", 30);
// 调用对象方法
$person->greet();
?>
文件操作:
php<?php
// 读取文件内容
$fileContent = file_get_contents("example.txt");
echo $fileContent;
// 写入文件内容
$file = fopen("example.txt", "w");
fwrite($file, "Hello, World!");
fclose($file);
?>
这些示例覆盖了一些常见的 PHP 编程主题。如果您对特定主题有任何疑问或需要更深入的示例,请随时告诉我!