我有下面的情況下讀取變量,我不知道如何作出這樣的:如何從另一個類
class A {
public fuction a1()
{
$time = date("Y-m-d H:i:s");
}
}
class B extends A {
public function b1()
{
// how to echo the variable "$time" in class B?
}
}
我有下面的情況下讀取變量,我不知道如何作出這樣的:如何從另一個類
class A {
public fuction a1()
{
$time = date("Y-m-d H:i:s");
}
}
class B extends A {
public function b1()
{
// how to echo the variable "$time" in class B?
}
}
你也可以試試這個
<?php
class A
{
public static function a1()
{
echo $time = date("Y-m-d H:i:s");
}
}
class B extends A
{
public function b1()
{
$this->a1();
}
}
$object = new B;
$object->b1();
這裏是2的方法:
First:
<?php
/**
* Class A
*/
class A
{
/**
* Class Property (Class Var)
* @var public
*/
public $time;
/**
* a1
* Set date time in class property $time
* @return [type] [description]
*/
public function a1()
{
$this->time = date("Y-m-d H:i:s");
}
}
/**
* Class B extends Class A
*/
class B extends A
{
/**
* b1
* Call Parent Class A method first to set date time
* then echo time output
* @return string Parent Class T$time value
*/
public function b1()
{
// first init the time value from parent class method
$this->a1();
// now show or get the parent class property
return $this->time;
}
}
/**
* Class Object B
* @var B
*/
$B = new B();
// call B Class method b1 to echo time
echo $B->b1();
Second:
<?php
/**
* Class A
*/
class A
{
/**
* Class Property (Class Var)
* @var public
*/
public $time;
/**
* a1
* Set date time in class property $time
* @return [type] [description]
*/
public function a1()
{
// set date time
$this->time = date("Y-m-d H:i:s");
// return set class property value
return $this->time;
}
}
/**
* Class B extends Class A
*/
class B extends A
{
/**
* b1
* Call Parent Class A method first to set date time
* then echo time output
* @return string Parent Class T$time value
*/
public function b1()
{
// first init the time value from parent class method
return $this->a1();
}
}
/**
* Class Object B
* @var B
*/
$B = new B();
// call B Class method b1 to echo time
echo $B->b1();
對於您可以聲明你的第一類變量沒有的功能。
class A()
{
protected static $time = date("Y-m-d H:i:s");
}
class B extends A
{
public function b1()
{
echo parent::$time;
}
}
您可以在代碼中的任何位置使用time變量而無需實例化A類。 「$ time」變量也不一定是靜態的。
調用父類方法就像這個'parent :: a1();'? –
'$ time'不存在於方法之外。您應該將其設置爲類屬性或從方法返回,以便可以使用該值。 – jeroen
只是想到,你可以調用直接函數a1()裏面b1()它會工作 –