저는 PHP가 매우 새롭습니다. OOP의 개념을 이해하지만 구문 론적으로, 다른 파일에서 상위 클래스를 확장하는 방법을 알지 못합니다. 여기 내 코드입니다 :PHP : 다른 파일에서 상위 클래스 호출하기
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 />';
}
}
?>
확장 된 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 line 4
. 모든 팁을 부탁드립니다.
'include_once 문을 파일을 포함 때문이다. –