I have A.php and B.php
A.php
<?php
error_reporting(E_ALL);
ini_set("display_errors",1);
class myClass
{
function hello()
{
return 'hello';
}
}
?>
B.php
<?php
error_reporting(E_ALL);
ini_set("display_errors",1);
require_once('/A.php');
$a = new myClass();
testing();
function testing()
{
echo $a ->hello();
}
?>
B.php inherits A.php ,
if i run B.php,but it show
“Fatal error: Call to a member function hello() on a non-object.”
So the question is simple, how can i correct this ,but “$a = new myClass();” is not inside the function, since in .NET world can do this, i believe PHP also possible.
And one more question is, what is the modify of function in A.php ,if i have not state private/public/protected?
A couple of things I would change here, I’ll explain in a moment.
A.php
B.php
When no access specifier is given on a method, it defaults to
public. However, it is generally better to just declare what you want the method to have. You will appreciate this if you find yourself actively coding in multiple languages as they will each have a different default.Right now the variable
$ais not in the scope of the function testing(). Allow me to rearrange your program and you shall see why. You could have written it, like so:B.php
You see, where
testing()is now defined,$adoes not exist. It hasn’t been defined yet. So it is not insidetesting()‘s scope. You’ll have to either define$ainsidetesting()or else pass it in as a parameter. In my first pass, I changed your code to define$ainsidetesting(). If you will need to use it in multiple functions, then I would suggest changingtesting()to take it as a parameter. Like this:Then pass it in this way: