user5854440
user5854440

Reputation: 281

PHP: calling a parent class from another file

I'm very new to PHP. I understand the concepts of OOP, but syntactically, I don't know how to extend a parent class from another file. Here is my code:

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();

?>

I'm using MAMP to run the code, and the following error keeps coming up: Cannot declare class Animals\Animal, because the name is already in use in /path/to/file/parent.php on line 4. All tips are appreciated.

Upvotes: 5

Views: 4865

Answers (3)

cteski
cteski

Reputation: 487

Main.php does not need to include parent.php, as extended-classes.php already includes it. Alternatively, you can use include_once or require_once instead of include.

Upvotes: 5

owais
owais

Reputation: 4922

For me its working by using.

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

it's due to including file again and again

Upvotes: 0

Sasan Farrokh
Sasan Farrokh

Reputation: 190

For including classes and constants , it's better to use

include_once  or   require_once

No more errors on re-declaring classes will thrown.

Upvotes: 0

Related Questions