Coding a character to go to the opposite side when exceeding the stage width

Basically, I’ve made it so that my “player” in my game doesn’t exceed the stage width (only moves along the x axis) and so when it gets to the edge it just stops. However, I want to make it so that if the player exceeds the width on the left side it will flow in from the right and vice versa. This is the code I have at the minute which is what stops it from leaving the stage area:

function movePlayer(e:Event):void {
    player.x = stage.mouseX;
    // Doesn't go off the right or left side.
    if (player.x < 0) {
        player.x = 0;
    } else if (player.x > (stage.stageWidth - player.width)) {
        player.x = stage.stageWidth - player.width;
    }
}

Is there a way I could edit this to get the desired effect? I found some code online, however I’m unsure as to how to wor it into my code as it includes a stageRef. Below is the code:

		//stay inside screen
		if (x > stageRef.stageWidth)
			x = 0;
		else if (x < 0)
			x = stageRef.stageWidth;

		if (y > stageRef.stageHeight)
			y = 0;
		else if (y < 0)
			y = stageRef.stageHeight;

Also if it’s relevant I’m using a phone’s accelerometer to move the player across the x-axis.

You already have the mechanism to detect when the player has reached the edge of the stage in your first code. Once the player reaches stage.stageWidth, simply set their position to 0 (and vice versa). This is shown in your second chunk of code. stageRef is presumably a reference to stage. People use such a reference in cases where stage is null (ie when the calling display object is not on the display list). Since stage is defined in your code, you can use it instead of stageRef.