I'm finding that these two PHP snippets yield the same result:
$arr['query']['confirm'] = 'y';
$text = t('Click here.');
$url = new Url('my_route.import', [], $arr); // Three arguments.
$link = Link::fromTextAndUrl($text, $url)->toString();
and
$arr['confirm'] = 'y'; // No "query" key.
$text = t('Click here.');
$url = Url::fromRoute('my_route.import', $arr); // Two arguments.
$link = Link::fromTextAndUrl($text, $url)->toString();
Is there any reason to prefer one approach over the other? Which is the more typical approach? Is there some general PHP rule of thumb that might apply, such as... always use a method on the class instead of instantiating an object with "new" whenever possible?
Url::__construct
method is thin; it just sets a few protected variables. TheUrl::fromRoute
method essentially just invokes the constructor to return a newUrl
object.