在PHP中声明对象和打印字符串


Declaring objects and printing strings in PHP

可捕获的致命错误:类HelloWorldClass的对象无法在第19行的/Applications/XAMPP/examplepfiles/htdocs/wisd_activity04c.php中转换为字符串

这个程序应该输出1."你好,世界!",红色/40px字体2.绿色/20px字体的"Hello World!",带下划线的

<?php 
    echo '60-334 ACTIVITY 4 PART 3/3<br><br>';
    class HelloWorldClass
    { 
        public $font_size;
        public $font_colour;
        public $hello_string;
        function __construct($size, $colour)
        { 
            $this->font_size = $size;
            $this->font_colour = $colour;
            $this->hello_string = "Hello World!";
        } 
        public function custom_show() 
        { 
            echo "<font color='"$this.font_colour'" size='"$this.font_size'">$this.hello_string</font>";
        }  
    } 
    class Sub_HelloWorldClass extends HelloWorldClass 
    { 
        function __construct($size, $colour)
        {
            parent::__contruct($font, $colour);
        }
        public function custom_show() 
        { 
            echo "<u><font color='"$this.font_colour'" size='"$this.font_size'">$this.hello_string</font></u>";
        } 
    } 
    $object = new HelloWorldClass('40px', 'red');
    $object->custom_show();
    $object = new Sub_HelloWorldClass('20px', 'green');
    $object->custom_show();
?>

这个答案来自您的第一次修订:

https://stackoverflow.com/revisions/28522294/1

你的代码中有几个错误:

1.缺少分号

$this->hello_string = "Hello World!"  //<- Missing semicolon at the end

2.类属性的访问错误

echo "<font color='"$this.font_colour'" size='"$this.font_size'">$this.hello_string</font>";
//...
echo "<u><font color='"$this.font_colour'" size='"$this.font_size'">$this.hello_string</font></u>";

我建议您将属性与字符串连接起来。如何连接?您必须使用串联运算符:.,并用引号确定字符串。

除此之外,您还必须使用运算符->访问类属性。有关访问类属性的更多信息,请参阅手册:http://php.net/manual/en/language.oop5.properties.php

所以你的代码应该是这样的:

echo "<font color='"" . $this->font_colour . "'" size='"" . $this->font_size . "'">" . $this->hello_string . "</font>";
//...                 ^ See here concatenation                   ^^ See here access of class property
echo "<u><font color='"" . $this->font_colour . "'" size='"" . $this->font_size . "'">" . $this->hello_string . "</font></u>";

3.带空格的类名

不能有带空格的类名:

class Sub_ HelloWorldClass extends HelloWorldClass  //So change just remove the space

有关类名的更多信息,请参阅手册:http://php.net/manual/en/language.oop5.basic.php

还有一句话:

类名可以是任何有效的标签,前提是它不是PHP保留字。有效的类名以字母或下划线开头,后跟任意数量的字母、数字或下划线。作为一个正则表达式,它可以这样表示:^[a-zA-Z_''x7f-''xff][a-zA-Z0-9_''x7f-''xff]*$

4.__construct() 中缺少's'

parent::__contruct($font, $colour);  //Missed 's' in construct

5.使用了错误的变量

function __construct($size, $colour)
{
    parent::__construct($font, $colour);  //Change '$font' to '$size'
}

旁注:

仅在暂存时打开文件顶部的错误报告:

<?php
    ini_set("display_errors", 1);
    error_reporting(E_ALL);
?>

这将为您提供有用的错误消息,很好地向您显示错误所在!