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.