【问题标题】:PHP Assigning a default Function to a classPHP 为类分配默认函数
【发布时间】:2012-01-26 14:30:35
【问题描述】:

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

我想创建一组具有默认功能的对象。

因此,我们可以只输出类/对象变量,而不是调用类中的函数,它可以执行默认函数,即 toString() 方法。

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

示例

class String {
     public function __construct() {  }

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

}

用法

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

【问题讨论】:

    标签: php object-to-string


    【解决方案1】:

    没有默认函数这样的东西,但是类有一些神奇的方法可以在某些情况下自动触发。在您的情况下,您正在寻找__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;
    ?>
    

    【讨论】:

    • 这不只是用来定义类在请求为字符串时应如何返回吗?
    • 我喜欢这种方法,非常清晰简单,不敢相信google没有找到。非常感谢..
    • 明白了,似乎我没有正确解释这个问题。 :D
    【解决方案2】:

    __toString() 在打印对象时被调用,即 echo $str。

    __call() 是任何类的默认方法。

    【讨论】:

      【解决方案3】:

      要么将toString函数代码放在__construct中,要么指向toString。

      class String {
           public function __construct( $str ) { return $this->toString( $str ); }
      
           //This I want to be the default function
           public function toString( $str ) { return (str)$str; }
      }
      
      print new String('test');
      

      【讨论】:

        猜你喜欢
        • 2022-01-04
        • 2021-09-12
        • 1970-01-01
        • 2022-10-23
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        • 2017-09-19
        • 1970-01-01
        相关资源
        最近更新 更多