如何从另一个类中读取变量

时间:2016-07-04 11:45:22

标签: php oop

我有以下情况,我不知道如何做到这一点:

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?
}
}

4 个答案:

答案 0 :(得分:2)

您可以 PHP parent关键字,return来自函数a1()的值。

所以你的代码看起来像这样,

<?php
class A
{
    public static function a1()
    {
        $time = date("Y-m-d H:i:s");
        return $time;
    }
}

class B extends A
{
    public function b1()
    {
        echo parent::a1();
    }
}

答案 1 :(得分:0)

你也可以尝试这个

<?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 :(得分:0)

这是两种方法:

<强> 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();

答案 3 :(得分:0)

为此,您可以在没有函数的情况下在第一个类中声明您的变量。

class A()
{
     protected static $time = date("Y-m-d H:i:s");

}

class B extends A 
{
    public function b1()
    {
        echo parent::$time;
    }
}

您可以在代码中的任何位置使用时间变量,而无需实例化A类。还有&#34; $ time&#34;变量不必是静态的。