0

I'm looking for a solution to use type hinting on a stream_socket_client() resource stream.

Researching this topic, I came across this question and its accepted answer, which somehow implies that what I'm looking for can't be done without moving away from stream_socket_client(), because stream_socket_client() returns a resource of the type stream. And even though resource is a primitive type, it's not supported by PHPs scalar type hinting.

However, maybe someone knows how to do this anyway or got an alternative to stream_socket_client() that works with type hinting.

Below you find an Email class broken down to the most basic code to work with and to give you an idea on how I'm using 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 */
    }
}

I'm using PHP 7.4, in case this matters.

Tobias Wicker
  • 617
  • 8
  • 12
  • 1
    "The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP." I don't see anything about it being explicitly prohibited like callable but I doubt it would be supported. Just use `/** @var resource $_connection */` instead. – Alex Barker Jan 06 '20 at 17:07
  • See for more information https://stackoverflow.com/questions/38429595/php-7-and-strict-resource-types – jspit Jan 06 '20 at 17:51

0 Answers0