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

时间:2013-02-09 16:49:50

标签: php class object methods

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

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

2 个答案:

答案 0 :(得分:0)

你错过了分号

$ this-&gt; 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

?>

答案 1 :(得分:0)

新代码的问题是您在定义 public $ day

后关闭了类定义
  

一级{       公共美元; } //使用最后一个大括号来关闭类!

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

卢西恩