问题
i am new to php oop
I have an two files Here is my code
1)info.php
public $bd, $db1;
class Connection {
function connect() {
$this->db = 'hello world';
$this->db1 = 'hi'
}
}
2) prd.php
require_once 'info.php'
class prdinfo {
function productId() {
echo Connection::connect()->$bd;
echo Connection::connect()->$db1;
}
$prd = new prdinfo ();
$prd->productId ();
how i can echo my var in 2nd class i have tried in that way but i am not getting proper output
Thanks
回答1:
It should be something like this.
info.php
class Connection {
// these two variable should be declared within the class.
protected $db; // to be able to access these variables from a diff class
protected $db1; // either their scope should be "protected" or define a getter method.
public function __construct() {
$this->connect();
}
private function connect() {
$this->db = 'hello world';
$this->db1 = 'hi';
}
}
prd.php
require_once 'info.php';
// you are accessing the Connection class in static scope
// which is not the case here.
class prdinfo extends Connection {
public function __construct() {
// initialize the parent class
// which in turn sets the variables.
parent::__construct();
}
public function productId() {
echo $this->db;
echo $this->db1;
}
}
$prd = new prdinfo ();
$prd->productId ();
This is a basic demonstration. Modify it as per your needs. More here - http://www.php.net/manual/en/language.oop5.php
来源:https://stackoverflow.com/questions/19217911/how-to-call-a-variable-from-one-class-function-to-another-class-function