2017-03-16 36 views
0

使用PHP 7.0.17,在class构造函数中设置属性对我无效。未在类中调用的PHP构造函数

class T 
{ 
    public $property; 
    function __contruct() 
    { 
     $this->property = "Test"; 
     print "I'm called :)"; 
    } 
} 

$t1 = new T(); 
print_r($t1); 

t.php

当我运行通过php t.php的代码,我得到:

T Object 
(
    [property] => 
) 

很显然,我希望I'm called :)印刷到终端和属性设置到Test。如图所示in this example on php.net

这是一个非常简单的问题,但我真的需要另一双眼睛。

+0

'$这个 - > property',不'$此 - > $ property' –

+0

'$此 - > $ property' - >注意你有'$'两次。这是打算吗? – Mjh

+3

另外,'__construct',而不是'__contruct' – roberto06

回答

2

变化$this->$property$this->property

变化contructconstruct

class T 
{ 
    public $property; 
    function __construct() 
    { 
     $this->property = "Test"; 
     print "I'm called :)"; 
    } 
} 

$t1 = new T(); 
print_r($t1); 
+3

*另外提及'contruct'中的输入错误* – Jer

+0

我必须等待8分钟才能接受您的答案。 – dotnetCarpenter

+0

@ C0dekid谢谢.. –

0

当对象访问类的属性(包括this),你不必再使用$

也就是说

$this->property='something'; 

从类外,

$t = new T(); 
$t->property='something';