2016-08-16 23 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_oncerequire_once而不是include

+0

This Works!感謝您的幫助。 – user5854440

0

對於包括類和常量,它更好地使用

include_once or require_once 

沒有更多的錯誤上再宣佈班會拋出。

0

對我來說,它的工作使用。

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

這是由於連連包括文件