2016-08-16 1 views
2

저는 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. 모든 팁을 부탁드립니다.

+0

'include_once 문을 파일을 포함 때문이다. –

답변

3

main.php에는 parent.php가 포함될 필요가 없습니다. extended-classes.php에 이미 포함되어 있습니다. 또는 include 대신 include_once 또는 require_once을 사용할 수 있습니다. 클래스와 상수를 포함한

+0

이 작품! 도와 주셔서 감사합니다. – user5854440

0

, 그것은 다시 선언 클래스에 발생합니다

include_once or require_once 

더 이상 오류를 사용하지 않는 것이 좋습니다.

0

나를 위해 그 작업을 사용하여.

require_once 'extended-classes.php'; 
require_once 'parent.php'; 

는 또 다시()`대신`()`파일을 보장하기 위해 한 번만 포함되어 포함의

당신은 사용해야
관련 문제