我在尝试做一些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
我不明白为什么它不起作用。。。我知道这肯定是愚蠢和基本的东西,但我就是看不出来…
新代码的问题是在定义public$day之后关闭类定义
a类{公共$day;}//类以最后一个花括号结束!
所以__constructor函数根本没有被调用!删除"public$day;"之后的大括号,并将其添加到__construct函数的定义之后。那就行了!
Lucian
中缺少分号
$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
?>