On hearing of Madeline's superstition, Porphyro hopes to take advantage of it. Madeline believes that if she performs certain rituals then, on the stroke of midnight of St. Agnes' Eve, she will experience a magical vision of her lover in her dreams. Porphyro wants to be that lover, hence his hiding out in a closet in Madeline's bedchamber until midnight strikes.
Porphyro loves Madeline, and she loves him. But Madeline's family are most certainly not enamored of Porphyro; to them, he is an enemy who must be killed. That explains why Porphyro has to be surreptitious, why he has to hide out in a closet. If he gets caught by Madeline's family, then it'll be curtains for him.
What we see here is a prime example of romantic love in action. Porphyro is so deeply in love with Madeline, so determined to make her his bride that he's prepared to risk his life to be with the woman he loves.
In due course, Porphyro and Madeline will run off together, but not before Madeline wakes from her enchanted dream and finds that the real Porphyro doesn't match the visionary one. But thanks to the power of magic, the two lovers are united in a mystical marriage as Porphyro enters into Madeline's ecstatic dream vision.