简体   繁体   中英

PHP: Can't use inheritance. It won't find the class

I reached the cap about inheritance but I can't use them, even when I try to use the examples from the book I'm learning. Even though all the files are on the same folder, the error is:

"Fatal error: Class 'mother' not found in C:\\Program Files (x86)\\EasyPHP-Devserver-16.1\\eds-www\\Learning\\classes\\son.php on line 2"

Let me show a exemple I created to explain.

FILE: mother.php :

    <?php
    class mother
    {
       public $word= "Hello!!!";

       function printWord()
       {
         echo $word;   
       }
     }
     ?>

FILE: son.php :

<?php 
  class son extends mother
   {
     function printWord()
     {
      parent::printWord();
     }
   }  
?>

FILE: test.php :

<?php
include 'son.php';
$test = new son();
$test->printWord();
?>

Results in:

ERROR: Fatal error: Class 'mother' not found in C:\\Program Files (x86)\\EasyPHP-Devserver-16.1\\eds-www\\Learning\\classes\\son.php on line 2

Why is this happening? Why it won't find the class if it is on the same folder ?!

You need to include the mother.php too. Otherwise it can't find the class as the error states.

Naive example:

test.php

<?php
include 'mother.php'
include 'son.php';
$test = new son();
$test->printWord();
?>

But there is even a better way

son.php

<?php 
  require_once 'mother.php'
  class son extends mother
   {
     function printWord()
     {
      parent::printWord();
     }
   }  
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM