|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2020-11-12 15:20 UTC] divinity76 at gmail dot com
Description:
------------
i wish casting to void was legal, doing the same thing as casting to void in C: a no-op. (used to shut up linters about unused variables)
there are some situations where you have to accept arguments that you don't use, or have to pass a variable by reference that you don't actually care about, and some linters may warn you about "this variable is declared but never used" or "this variable is written to but never read", for example CURLOPT_HEADERFUNCTION: the first argument is the curl handle and the 2nd argument is the header, some code only cares about the header, but have to accept the curl argument too just to match the CURLOPT_HEADERFUNCTION callback signature (in my experience, the handle argument is only useful when using the curl_multi api, and not useful when using the non-multi api)
Test script:
---------------
<?php
$recieved_headers = [];
$curlopts = array(
CURLOPT_HEADERFUNCTION => function ($ch, string $header) use (&$recieved_headers): int {
(void) $ch;
$recieved_headers[] = $header;
return strlen($header);
}
);
function f(&$val1, &$val2, &$val3)
{
// lets pretend this function writes to val1/val2/val3
}
$data_i_need = null;
$data_i_dont_need = null;
f($data_i_need, $data_i_dont_need, $data_i_dont_need);
(void)$data_i_dont_need;
Expected result:
----------------
(blank)
Actual result:
--------------
Parse error: syntax error, unexpected '$ch' (T_VARIABLE) in /in/uWlu5 on line 5
Process exited with code 255.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Dec 05 21:00:01 2025 UTC |
another usecase: when you want to ForEach() keys but don't care about the value: foreach($a as $key=>$unused){ (void)$unused; // ... } - sure some might argue that foreach(array_keys($a) as $key){} can be used instead.. but that comes at a performance penalty if nothing elseAs Nikic said, this would need to be discussed on list, and in particular: > used to shut up linters about unused variables This is a code style check, rather than a definite error. I (and possbly others) have quite strong views against adding complexity to PHP core to fix things that are only problems when you apply certain style checking rules. I can see it would make your life easier, but it's added tech debt for a problem you are opting into. I realise that going through projects and marking variables as unused in every place where it is appropriate to not use that variable is annoying, so here, have a function: function unused(mixed $_) {} You can add this to a project, and just tell your linter to ignore the unused variable once.