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の代わりにinclude_onceまたはrequire_onceを使用することもできます。

+0

これは機能します!お手伝いありがとう。 – user5854440

0

クラスや定数などのために、それは再宣言クラスのこれ以上のエラーがスローされません

include_once or require_once 

を使用することをお勧めします。

0

私の場合は、を使用して作業しています。

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

それは何度も何度も() `だけでなく`() `あなたのファイルを確実にするために、一度だけ含まれているが含まの

あなたが使用する必要があります
関連する問題