php - 在类中设置变量

标签 php oop constructor

我想做这样的事情:

<?php
    $editor = new editor('reply.php?topic=100', 'simple');
    echo $editor;
?>

但是我不熟悉 OOP/类,但我想在类中做这样的事情:

<?php
class editor($url, $type)
{
    if($type == 'simple'){
        ?>
            <form action="<?php echo $url; ?>">
                ...
            </form>
        <?php
    }
    else
    {
        ...
    }
}
?>

当然,这是不对的。但我怎样才能做到呢?因为我对构造函数和析构函数等一无所知......

最佳答案

$editor = new editor('reply.php?topic=100', 'simple');
echo $editor;

class editor
{
    private $url;
    private $type;

    public function __construct($url, $type)
    {
        $this->url = $url;
        $this->type = $type;
    }

    public function __toString()
    {
        if($this->type == 'simple'){
            return '<form action="' . $this->url . '"></form>';
        } else {
            return 'foobar';
        }
    }
}

关于php - 在类中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5448928/

相关文章:

c# - 有没有办法将类内的字段组划分为 "sub structures"

String 对象改变时的 Java String Immutability 存储

java - 创建对象数组时的构造函数

c# - 继承和构造函数中的错误

php - 与 python 字典等效的 php 结构是什么?

php - 将 Propel 转换为带有链接实体的 JSON

c++ - 在 Smalltalk 中设计事务管理器

c++ - 选择构造函数的更好模式

php - Cakephp 表单输入自动完成功能

php - 在使用 PHP 7.0.6 的 Wampserver 3.0.4 上安装 Joomla 3.5.1 时出错