首页 > 解决方案 > 流资源的类型提示 (stream_socket_client)

问题描述

我正在寻找一种在stream_socket_client()资源流上使用类型提示的解决方案。

研究这个主题时,我遇到了这个问题及其接受的答案,这在某种程度上暗示我正在寻找的东西如果不离开就无法完成stream_socket_client(),因为stream_socket_client()返回 aresource的类型stream。即使resource是原始类型,PHP 标量类型提示也不支持它。

但是,也许有人无论如何都知道如何执行此操作,或者stream_socket_client()可以使用类型提示来替代它。

下面你会找到一个Email分解为最基本的代码的类,并让你了解我是如何使用stream_socket_client().

class Email {

    private /* WHAT TYPE HINT TO PUT HERE? */ $_connection = null;

    public function sendEmail() {
        // set email server details
        $smtpServer = // set your smtp server address
        $smtpPort = // set your smtp server port;

        // context options for ssl connection
        $contextOptions = array(
            'ssl' => array(
                'verify_peer' => true,
                'verify_peer_name' => true
            )
        );

        $context = stream_context_create($contextOptions);

        // establish connection
        $this->_connection = stream_socket_client("tcp://$smtpServer:$smtpPort", $error_no, $error_str, 20, STREAM_CLIENT_CONNECT, $context);

        // enable TLS
        stream_socket_enable_crypto($this->_connection, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT)

        /* in the real world, you'd wanna make sure the connection has been established, 
           enabling crypto succeeded and afterwards send the email by writing smtp commands to the stream */
    }
}

我正在使用 PHP 7.4,以防万一。

标签: phpstreamresourcestype-hintingstream-socket-client

解决方案


推荐阅读