Php 在多个类周围使用键
基本上,我想使用一个键,并且能够从另一个类调用一个类中的函数 也许我提供的例子能更好地解释我的意思。我想到了Php 在多个类周围使用键,php,Php,基本上,我想使用一个键,并且能够从另一个类调用一个类中的函数 也许我提供的例子能更好地解释我的意思。我想到了const,但我无法从那里修改它 我考虑将密钥解析为构造函数,我只是想知道是否还有其他更好的方法,因为它将在多个类中使用 Class1.php <?PHP class Class1 { public $key; public function setKey($k) { $this->key = $k; } publi
const
,但我无法从那里修改它
我考虑将密钥解析为构造函数,我只是想知道是否还有其他更好的方法,因为它将在多个类中使用
Class1.php
<?PHP
class Class1 {
public $key;
public function setKey($k)
{
$this->key = $k;
}
public static function getKey()
{
return $this->key; // this won't work because static
}
}
?>
<?PHP
class Class2 {
public function __construct()
{
echo Class1::GetKey(); // Need to retrieve the key here
}
}
?>
<?PHP
require_once("Class1.php");
require_once("Class2.php");
$c1 = new Class1();
$c1->setKey("thekey");
$c2 = new Class2();
?>
您可以使用静态属性,这样您就可以在类之外使用它,并且可以在以后更改它。例如:
class Class1
{
static $key = 'ABC';
}
class Class2
{
public function __construct()
{
echo 'Original key: ' . Class1::$key . '<br />';
Class1::$key = '123';
echo 'New key: ' . Class1::$key;
}
}
new Class2();
但是为了保持封装概念,我建议您尝试使用get
和set
方法。实现这一点的一种方法是将存储公共数据的类转换为。本质上,您只需添加一种方法来一致地返回类的相同实例:
class MyClass
{
/**
* @var MyClass
*/
protected static $instance;
protected $key;
public static getInstance()
{
if (!self::$instance) {
self::$instance = new MyClass();
}
return self::$instance;
}
public function setKey($k)
{
$this->key = $k;
}
public static function getKey()
{
return $this->key;
}
}
然后像这样使用它:
// Both of these use the same instance of MyClass
MyClass::getInstance()->setKey('hello');
MyClass::getInstance()->getKey();
这允许您使用实例属性和方法编写类,而不必使所有内容都是静态的
进一步阅读:
让你的第二课堂变成这样
<?PHP
class Class2 {
public function __construct(Class1 $a1)
{
echo $a1->GetKey(); // Need to retrieve the key here
}
}
?>
并将index.php设置为如下方式
<?PHP
require_once("Class1.php");
require_once("Class2.php");
$c1 = new Class1();
$c1->setKey("thekey");
$c2 = new Class2($c1);
谢谢,我想这就是我要说的。谢谢你的回复。谢谢你的回复。
<?PHP
require_once("Class1.php");
require_once("Class2.php");
$c1 = new Class1();
$c1->setKey("thekey");
$c2 = new Class2($c1);