php - Class Inheritance Problem -
i have a.php , 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 run b.php,but show "fatal error: call member function hello() on non-object."
so question simple, how can correct ,but "$a = new myclass();" not inside function, since in .net world can this, believe php possible.
and 1 more question is, modify of function in a.php ,if have not state private/public/protected?
a couple of things change here, i'll explain in moment.
a.php
<?php error_reporting(e_all); ini_set("display_errors",1); class myclass { // here, access modifier. public function hello() { return 'hello'; } } ?> b.php
<?php error_reporting(e_all); ini_set("display_errors",1); require_once('/a.php'); testing(); function testing() { // here, change variable defined place in scope. $a = new myclass(); echo $a ->hello(); } ?> when no access specifier given on method, defaults public. however, better declare want method have. appreciate if find actively coding in multiple languages each have different default.
right variable $a not in scope of function testing(). allow me rearrange program , shall see why. have written it, so:
b.php
<?php function testing() { echo $a ->hello(); } error_reporting(e_all); ini_set("display_errors",1); require_once('/a.php'); $a = new myclass(); testing(); ?> you see, testing() defined, $a not exist. hasn't been defined yet. not inside testing()'s scope. you'll have either define $a inside testing() or else pass in parameter. in first pass, changed code define $a inside testing(). if need use in multiple functions, suggest changing testing() take parameter. this:
function testing(myclass $a) { echo $a->hello(); } then pass in way:
$a = new myclass(); testing($a);
Comments
Post a Comment