0

我在尝试做一些 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

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

4

2 回答 2

0

新代码的问题是您在定义public $day之后关闭了类定义

A类{公共$天;} // 类被最后一个大括号关闭!

所以 __constructor 函数根本没有被调用!删除“public $day;”后面的大括号 并将其添加到 __construct 函数的定义之后。然后它应该工作!

卢西安

于 2013-02-10T11:08:48.730 回答
0

你错过了一个分号

$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

?>
于 2013-02-09T20:22:58.827 回答