PHP 为类分配默认函数 [英] PHP Assigning a default Function to a class

查看:21
本文介绍了PHP 为类分配默认函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 PHP 比较陌生,但已经意识到它是一个强大的工具.所以请原谅我的无知.

Im relatively new to PHP but have realized it is a powerfull tool. So excuse my ignorance here.

我想用默认函数创建一组对象.

I want to create a set of objects with default functions.

因此,与其调用类中的函数,不如只输出类/对象变量,它可以执行默认函数,即 toString() 方法.

So rather than calling a function in the class we can just output the class/object variable and it could execute the default function i.e toString() method.

问题:有没有办法在类中定义默认函数?

The Question: Is there a way of defining a default function in a class ?

示例

class String {
     public function __construct() {  }

     //This I want to be the default function
     public function toString() {  }

}

使用

$str = new String(...);
print($str); //executes toString()

推荐答案

没有默认函数这样的东西,但是有一些神奇的方法可以在某些情况下自动触发类.在您的情况下,您正在寻找 __toString()

There is no such thing as a default function but there are magic methods for classes which can be triggered automatically in certain circumstances. In your case you are looking for __toString()

http://php.net/manual/en/language.oop5.magic.php

手册中的示例:

// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo)
    {
        $this->foo = $foo;
    }

    public function __toString()
    {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

这篇关于PHP 为类分配默认函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆