如何在PHP中初始化构造函数中的变量(How to initialize variable in constructor in PHP)

编程入门 行业动态 更新时间:2024-10-28 19:22:17
如何在PHP中初始化构造函数中的变量(How to initialize variable in constructor in PHP)

我正在写这个简单的代码,不知道构造函数的问题是:

class Animal { public $_type; public $_breed; public function __construct ($t, $b) { echo "i have initialized<br/>"; $this ->_type = $t; $this ->_breed = $b; echo "type is " .$_type. "<br/>"; echo "breed is " .$_breed. "<br/>"; } public function __destruct () { echo "i am dying"; } } $dog = new Animal("Dog", "Pug");

I am writing this simple code and do not know what the issue with constructor is:

class Animal { public $_type; public $_breed; public function __construct ($t, $b) { echo "i have initialized<br/>"; $this ->_type = $t; $this ->_breed = $b; echo "type is " .$_type. "<br/>"; echo "breed is " .$_breed. "<br/>"; } public function __destruct () { echo "i am dying"; } } $dog = new Animal("Dog", "Pug");

最满意答案

试试这个(注意回声线):

class Animal { public $_type; public $_breed; public function __construct ($t, $b) { echo "i have initialized<br/>"; $this->_type = $t; $this->_breed = $b; //You have to use '$this' keyword to access //class attibutes: echo "type is " . $this->_type . "<br/>"; echo "breed is " . $this->_breed . "<br/>"; } public function __destruct () { echo "i am dying"; } }

Try this (note the echo lines):

class Animal { public $_type; public $_breed; public function __construct ($t, $b) { echo "i have initialized<br/>"; $this->_type = $t; $this->_breed = $b; //You have to use '$this' keyword to access //class attibutes: echo "type is " . $this->_type . "<br/>"; echo "breed is " . $this->_breed . "<br/>"; } public function __destruct () { echo "i am dying"; } }

更多推荐

本文发布于:2023-07-22 07:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1217944.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   变量   函数   如何在   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!