PHP基础语法例子:
- 输出Hello World
<?php
// 常规方式定义函数并调用
function add($x,$y){
return $x+$y;
}
echo add(2,3); //输出"5"
// 使用匿名函数
$add = function($x,$y){
return $x+$y;
};
echo $add(2,3); //输出"5"
?>
<?php
interface Shape {
public function getArea();
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
}
$rec = new Rectangle(5,6);
echo "The area of rectangle is ".$rec->getArea(); //输出"The area of rectangle is 30"
?>
匿名函数
<?php
namespace MyNamespace;
class MyClass{
public function sayHello(){
echo "Hello from MyNamespace!";
}
}
// 使用一个命名空间别名来避免命名冲突
use MyNamespace\MyClass as MC;
// 实例化对象并调用方法
$myObj = new MC();
$myObj->sayHello();
?>
接口
<?php
class Person{
public static $count = 0;
public function __construct() {
self::$count++;
}
public static function getCount() {
return self::$count;
}
}
$person1 = new Person();
echo Person::getCount(); // 输出"1"
$person2 = new Person();
echo Person::getCount(); // 输出"2"
?>
命名空间
<?php
class Person{
public $name; //公有属性,任何地方都可以访问
private $age; //私有属性,只能在类的内部访问
protected $address; //受保护属性,只能在本类和子类中访问
public function sayHello(){
echo "Hello, my name is ".$this->name;
}
private function getAge(){
return $this-&g