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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×