# Problem with passsing options through customized class interface \myclsset using pgfkeys

My intention is to create a class with a interface setup command \myclsset

\documentclass{myclass}

\myclsset{key1=val1, key2=val2, ..} % key-value list

\begin{document}
...
\end{document}


where \myclsset, acting as document interface, can be smoothly used anywhere after \documentclass{} call. I choose pgfkeys to implement for some specific reasons.

Here's the .cls file, in which I try to create a choice key whose value is a boolean \if switch that does formatting work for me:

\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{myclass}[2019/03/27 My Test Class]

\RequirePackage{pgfkeys,pgfopts}

\newif\ifmyclass@section@italic
\pgfkeys{%
/myclass/.cd,
section/.is choice,
section/italic/.code = {\myclass@section@italictrue}
}

% Set up the interface for the document class.
\newcommand*{\myclsset}[1]{%
\pgfqkeys{/myclass}{#1}%
}

\DeclareOption*{\PassOptionsToClass{\CurrentOption}{article}}
\ProcessOptions

\ProcessPgfOptions{/myclass} % Processing options through pkg/class

\ifmyclass@section@italic
\titleformat*{\section}{\itshape} % make section title italic
\else
\relax
\fi
\endinput


The MWE shows that \documentclass[...]{myclass} can work:

\documentclass[section = italic]{myclass}

\begin{document}
\section{A Topic}
\end{document}


However, this pattern:

\documentclass{...}
\myclsset{...} % key-value list in braces


does not work at all:

\documentclass{myclass}

\myclsset{section = italic}

\begin{document}
\section{A Topic}
\end{document}


The section title does not switch to italic. So the question is what do I miss to fail to make \myclsset work?

The problem is that your \ifmyclass@section@italic condition is only checked when the class file is loaded, but your \myclsset call happens after that. \myclsset will then set the switch to true correctly, the condition if never checked again, though.

What you want to do instead is to defer all the code that handles the current key setting until the actual document begins. For this purpose there's the \AtBeginDocument{...} hook.

Your section title handling would then look like

\newcommand\myclass@handle@keys{%
\ifmyclass@section@italic
\titleformat*{\section}{\itshape} % make section title italic
\else
\relax
\fi
}
\AtBeginDocument{\myclass@handle@keys}


No matter where in the preamble the key setting happens then, they will be processed correctly at the begin of the main part of the document.