PHP面向对象编程

AB是两个平级目录,A目录下有个UserModel.phpModel.php,UserModel 继承自Model.php;B目录下有个调用者index.php

Model.php

<?php
class Model {

   public function getMsg() {
        return "this parent message";
   }
}

UserModel.php

<?php
require 'Model.php';
class UserModel extends Model {

    private $name;

    public function __construct($name) {
        echo parent::getMsg().'<br>'; //调用父类方法
        $this->name = $name;
    }

    public function setName($name) {
        $this->name = $name;
    }

     public function getName() {
        return $this->name;
    }

    public static function getStaticFun() {
        echo "hello static";
    }
}

index.php

<?php

require "../UserModel.php";

$User = new UserModel('Leno.Li');
echo $User->getName().'<br>';

$User->setName('Rick.Xu');

echo $User->getName()."<br>";

UserModel::getStaticFun(); //调用类的静态方法
echo "<br>";
$User->getStaticFun();  //通过实例调用静态方法
//UserModel.getStaticFun(); error

Output

this parent message
Leno.Li
Rick.Xu
hello static
hello static