我是 PHP 的新手。我了解 OOP 的概念,但在语法上,我不知道如何从另一个文件扩展父类。这是我的代码:
parent.php
<?php
namespace Animals;
class Animal{
protected $name;
protected $sound;
public static $number_of_animals = 0;
protected $id;
public $favorite_food;
function getName(){
return $this->name;
}
function __construct(){
$this->id = rand(100, 1000000);
Animal::$number_of_animals ++;
}
public function __destruct(){
}
function __get($name){
return $this->$name;
}
function __set($name, $value){
switch($name){
case 'name' :
$this->$name = $value;
break;
case 'sound' :
$this->$name = $value;
break;
case 'id' :
$this->$name = $value;
break;
default :
echo $name . " not found";
}
}
function run(){
echo $this->name . ' runs <br />';
}
}
?>
extended-classes.php
<?php
namespace mammals;
include 'parent.php';
use Animals\Animal as Animal;
class Cheetah extends Animal{
function __construct(){
parent:: __construct();
}
}
?>
main.php
<?php
include 'extended-classes.php';
include 'parent.php';
use Animals\Animal as Animal;
use mammals\Cheetah as Cheetah;
$cheetah_one = new Cheetah();
$cheetah_one->name = 'Blur';
echo "Hello! My name is " . $cheetah_one->getName();
?>
我正在使用 MAMP 运行代码,但不断出现以下错误:Cannot declare class Animals\Animal, because the name is already in use in/path/to/file/parent.php on第 4 行
。感谢所有提示。
最佳答案
Main.php 不需要包含 parent.php,因为 extended-classes.php 已经包含了它。或者,您可以使用 include_once
或 require_once
而不是 include
。
关于PHP:从另一个文件调用父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38984928/