繁体   English   中英

在PHP中如何从另一个类调用属性的方法

[英]In PHP how do I call the method of an attribute from another class

尝试做一些Php对象时遇到一个小问题。

我有这些课:

class a
{
    public $day;

    function __construct(){
        $this->day = new DateTime("now");
    }
}

class b
{
    public $test;

    function __construct(){
        $this->test = new a()
    }
    function myFunc(){
        $this->test->day->format('Y-m-d');
    }
}

调用myFunc时出现此错误:

致命错误:在非对象上调用成员函数format()

如何从类“ b”中调用类“ a”中包含的对象属性的方法?

编辑:好的,所以我实际上使上面的代码比我实际要的要简单,以便将其发布到此处,这样错误并没有通过...这是一个更接近我的代码,并且显示了错误我在说

<?php
date_default_timezone_set('America/Chicago');
class a
{
    public $day;
}

function __construct($day = "now")
{
    $this->day = new DateTime($day);
}

class b
{
public $test;

function __construct(){
    $this->test = new a();
    }   
function myFunc(){
    echo $this->test->day->format("Y-m-d");
    }   
}
$bclass = new b();
$bclass->myFunc();
?>

这正是执行它时得到的:

 ( ! ) Fatal error: Call to a member function format() on a non-object in C:\\wamp\\www\\axpo\\newPHPClass.php on line 21 Call Stack # Time Memory Function Location 1 0.0023 256080 {main}( ) ..\\newPHPClass.php:0 2 0.0024 257128 b->myFunc( ) ..\\newPHPClass.php:25 

我不明白为什么它不起作用...我知道这肯定是愚蠢而基本的,但是我只是看不到...

你在缺少分号

$ this-> test = new a();

并且您必须返回或回显类b的myFunc()中的值才能对其进行处理。 看看这个:

<?php
class a
{
    public $day;

    function __construct(){
        $this->day = new DateTime("now");
    }
}

class b
{
    public $test;

    function __construct(){
        $this->test = new a(); // Added a semicolon !
    }
    public function myFunc(){
       return $this->test->day->format('Y-m-d'); // Return the value
    }
}

$b= new b();
echo $b->myFunc(); // echo the returned value from the function

?>

新代码的问题在于,您在定义公共$ day之后关闭了类定义

类别{ } //类用最后一个花括号关闭!

因此,根本不会调用__constructor函数! 在“ public $ day;”之后删除花括号。 并将其添加到__construct函数的定义之后。 然后它应该工作!

露西安

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM