Jump to content
Sign in to follow this  
gongpex

php use and namespace class not found

Recommended Posts

Hello everyone

First of all Happy New Year 2019 hope y'all successful to achieve y'all's target in this year.

I created code to test namespace and use in php

like this :

<?php
namespace Base;

class Section{

	function test(){
		echo 'aaa';
	}
	
}
?>

file on above is Section.php

<?php
namespace Base2;

class Base2 extends Base\Section {

	function test(){
		$class = new Section();
		$class->aaa();
	}
	
}
$ans = new Base2();
$ans->test();
?>

this file is : Base2.php

when I run Base2.php it always Fatal error: Class 'Base2\Base\Section' not found in C:\Apache24\htdocs\branch\learn\Base2.php on line 4

Q : Is there something wrong with my code?

please help

Thanks

Share this post


Link to post
Share on other sites

First, you need to include the file of the class you're going to use. The second thing is that you have to have a leading backslash to indicate that Base is in the global scope.

<?php
namespace Base2;
require_once 'path/to/Section.php';

class Base2 extends \Base\Section {
  // ...
}

I am not sure why you are both extending a class and then instantiating the same class inside the extended object. You either do one or the other, not both. In this case, just delete the test() method from Base2 because it already has this method inherited.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...