[英]how to call a variable from one class function to another class function
i am new to php oop 我是php oop的新手
I have an two files Here is my code 我有两个文件这是我的代码
1)info.php 1)info.php
public $bd, $db1;
class Connection {
function connect() {
$this->db = 'hello world';
$this->db1 = 'hi'
}
}
2) prd.php 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 我如何在二等课堂上回应我的var我已经尝试过这种方式,但是我没有得到正确的输出
Thanks 谢谢
It should be something like this. 应该是这样的。
info.php 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 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
更多内容-http: //www.php.net/manual/zh/language.oop5.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.