<?php
namespace Fatherspace {
const FLAG = 123;
class Person
{
protected $weight = 60;
public function say()
{
echo "person hello" . PHP_EOL;
}
}
interface Animal
{ // 接口中的方法不能有方法体
public function eat();
}
}
namespace MyNamespace {
const LastName = "Yao";
class Student extends \Fatherspace\Person implements \Fatherspace\Animal
{
const FirstName = "Xiaoming"; // 常量
public static $name = "laoer";
public static $age = 20;
public $data = array();
public function __construct($name, $age)
{
echo "construct" . PHP_EOL;
$this->name = $name;
$this->age = $age;
}
public function __destruct()
{
echo "destruct" . PHP_EOL;
}
public function __toString()
{
return "name: " . $this->name . ", age: " . $this->age;
}
public function __get($property)
{
if (array_key_exists($property, $this->data)) {
return $this->data[$property];
} else {
return "no such property $property" . PHP_EOL;
}
}
public function __set($property, $value)
{
$this->data[$property] = $value;
}
public function say()
{
parent::say();
echo "hello, " . $this->name . PHP_EOL;
}
public function __call($method, $arguments)
{
echo "no such method $method" . PHP_EOL;
}
public function get_weight()
{
return $this->weight;
}
public static function get_name_age()
{ // 静态方法访问静态属性
return "name: " . self::$name . ", age: " . self::$age;
}
public function eat()
{
echo "eat" . PHP_EOL;
}
}
}
namespace {
echo MyNamespace\LastName . PHP_EOL; // 访问其他命名空间的常量, 这种方式只能访问常量和类和接口
$stu = new MyNamespace\Student("laoer", 20);
echo $stu . PHP_EOL;
$stu->say();
$stu->hobby = "basketball"; // 通过__set 方法新增属性
echo $stu->hobby . PHP_EOL; // 通过__get 方法获取属性
echo $stu->weight . PHP_EOL; // protected属性不能在类外部访问
echo $stu->get_weight() . PHP_EOL; // 通过方法访问
echo MyNamespace\Student::get_name_age() . PHP_EOL; // 静态方法访问
$stu->test_method(); // 不存在的方法
$stu->eat(); // 实现接口中的方法
echo MyNamespace\Student::FirstName . PHP_EOL; // 访问常量和访问静态方法一样
echo "xxxxxx" . PHP_EOL;
use Fatherspace\Person;
$man1 = new Person();
$man1->say();
}