【问题标题】:How to check if a construct of a class exists?如何检查一个类的构造是否存在?
【发布时间】:2014-09-29 09:13:34
【问题描述】:

是否有检查某个类中是否存在构造函数的函数/方法?我尝试了 function_exists() 方法/函数,但它看起来不起作用:

<?php

class Test {

    public function __construct() {
        echo 'Construct loaded.<br />';

        if (function_exists('__construct'))
            echo 'Function exists.';
        else
            echo 'Function doesn\'t exists.';
    }

}

new Test;

更新(感谢大家,这个有效):

<?php

class Test {

    public function __construct() {
        echo 'Construct loaded.<br />';
    }

}

$t = new Test;

if (method_exists($t, '__construct'))
    echo 'Function exists.';
else
    echo 'Function doesn\'t exists.';

更新 #2

因为我在创建新对象之前需要这个,所以我最终得到了这段代码(我添加了它以防将来有人会读到这个):

<?php

class Test {

    public function __construct() {
        echo 'Construct loaded.<br />';
    }

}

//$t = new Test;

if (method_exists('Test', '__construct'))
    echo 'Function exists.';
else
    echo 'Function doesn\'t exists.';

【问题讨论】:

  • function_exists 正在检查是否存在 全局函数,而不是类方法....尝试使用 method_exists()
  • 因为function_exists('__construct') 正在检查函数,而不是类方法。
  • 我想这只是一个例子,但我确实希望你没有检查其内部是否存在构造函数......?!
  • @deceze no...这只是为了这个例子。否则就没有意义了。 :D
  • @tastro 如果您找到了function_exists,并查看了手册(当然您已经查看了),则有一个“请参阅”部分,其中总是包含一些有用的内容。

标签: php constructor exists


【解决方案1】:

改用method_exists

if (method_exists(self, '__construct')) {

}

self 在您的情况下是 __CLASS__Test 类。

【讨论】:

  • 为了完整起见,也可以使用reflection :-)
  • 感谢您指出这一点。我以前从未使用过ReflectionClass :)
  • 由于马克贝克没有发布他的答案作为答案,我投票给你作为我的接受。谢谢。
  • @mTorres 谢谢!很高兴知道我有更多选择......但现在我会选择method_exists()
  • 哦,为了完整性:is_callable('classname::__construct', true) 也应该工作 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多