I want to define a custom environment, which takes an optional parameter, and I want be able to link to the environment using nameref. To this end, I tried something similar to the following MWE:
\documentclass{article}
\usepackage{hyperref}
\usepackage{caption}
\usepackage{trace}
\newenvironment{myenv}[1][]
{
% define auxiliary variable, as #1 is not allowed in the end part of a newenvironment
\def\myarg{#1}
}
{
\captionof{table}{\myarg}
}
\begin{document}
\begin{myenv}[A title.\label{myenv:title}]
Something that pretends to be a table.
\end{myenv}
\traceon
\nameref{myenv:title}
\traceoff
\end{document}
Tracing shows hyperref is defining the following macro:
\r@myenv:title ->{1}{1}{\myarg \relax }{table.1}{}
which, predictably, gives me an
! Undefined control sequence.
<argument> \myarg
I guess that makes sense, as \myarg is only defined in the scope of the environment. My question is now: How do I force \myarg to expand before it is passed to \r@myenv:title?
I have already taken a look at a similar question about expansion, but was not able to adapt that solution.

%after an opening brace, that would otherwise include a space in your code. – Skillmon Jun 24 '19 at 13:39