The map you describe in your question is
\begin{align*}
\phi : [X, Y]\times[Y, Z] &\to [X, Z]\\
([\alpha], [\beta]) &\mapsto [\beta\circ\alpha].
\end{align*}
Let $X$ be an $n$-dimensional CW complex and $Z$ a CW complex. By the cellular approximation theorem, any continuous map $f : X \to Z$ is homotopic to a cellular map $\hat{f} : X \to Z$, in particular, $\hat{f}(X) \subseteq Z^{(n)}$ where $Z^{(n)}$ denotes the $n$-skeleton of $Z$. So there is a map $g : X \to Z^{(n)}$ satisfying $\hat{f} = i\circ g$ where $i : Z^{(n)} \to Z$ denotes the inclusion. Letting $Y = Z^{(n)}$, we see that for any $[f] \in [X, Z]$ we have $[f] = [\hat{f}] = [i\circ g] = \phi([g], [i])$. Therefore $\phi$ is surjective.
The example you gave, namely $Y = S^n$ and $Z = K(\mathbb{Z}, n)$, is a special case of the example above. To see this, we will build a CW complex $Z$ which is a $K(\mathbb{Z}, n)$ and has $S^n$ as its $n$-skeleton.
Recall that $S^n$ has first non-trivial homotopy group $\pi_n(S^n) = \mathbb{Z}$ and that it has non-trivial higher homotopy groups (unless $n = 0, 1$). One can glue on cells of dimension at least $n + 2$ to obtain a space $Z$ with $\pi_i(Z) = 0$ for $i > n$. As $Z$ is obtained from $S^n$ by adding only cells of dimension at least $(n + 2)$, we have $Z^{(n+1)} = Z^{(n)} = S^n$. By the cellular approximation theorem, for $i \leq n$, $\pi_i(Z) = \pi_i(Z^{(n+1)}) = \pi_i(S^n)$. Therefore $Z$ has only one non-zero homotopy group, namely $\pi_n(Z) = \mathbb{Z}$, so $Z = K(\mathbb{Z}, n)$.