In a php page i want to use a class that extend another class, but i can't. I got Abb.php page like this
<?php
namespace NormalPage;
use CommonClasses\Aaa;
require "Aaa.php";
$xxx=new Abb();
$xxx->SayHelloB();
class Abb extends Aaa
{
public function SayHelloB()
{
echo "Hello B";
}
}
In the same directory i got the Aaa.php file liek this
<?php
namespace CommonClasses;
class Aaa
{
public function SayHello()
{
echo "<html>Hello!</html>";
}
}
When i browse Abb.php i got "Error: Class "NormalPage\Abb" not found in Abb.php on line 6". If i modify "Abb.php" like this (Abb doesn't extend Aaa anymore)
<?php
namespace NormalPage;
use CommonClasses\Aaa;
require "Aaa.php";
$xxx=new Abb();
$xxx->SayHelloB();
class Abb //extends Aaa (Abb does't extends Aaa)
{
public function SayHelloB()
{
echo "Hello B";
}
}
The page work correctly. Where is the mistake? I'd like to have a base class to extends in every page. I know it isn't the best way to implement oop page in php, but i need to convert an old procedural site in a "little bit modern" style and i need to do this without say to my customer "no more implementation for a year, we must rewrite evrything". I would like to "migrate" the site page by page.
You need to define the Abb
class before instantiating it, so move class Abb extends Aaa { ... }
so it's before $xxx=new Abb();
:
<?php
namespace NormalPage;
use CommonClasses\Aaa;
require "Aaa.php";
class Abb extends Aaa
{
public function SayHelloB()
{
echo "Hello B";
}
}
$xxx=new Abb();
$xxx->SayHelloB();
That your code does work without the extends ...
is apparently a bug/oddity in php: for a class without extends ...
it does not matter if the class is defined before or after instantiation. A class with extends ...
may or may not work if it is defined after instantiation, this seems to depend on where its parent class is located, the exact behaviour is not well documented.
See also: https://planetjon.ca/php-class-hoisting-bug-3096 and https://www.npopov.com/2021/10/20/Early-binding-in-PHP.html