为什么数据仅在foreach循环中显示但在其外部是非对象?

I'm new to PHP and confused about this bit ..

When I have this it shows the data

<?php foreach ($profile as $p):?>
    <?php echo $profile->custom_url;?>
                    <?php endforeach?>

But when I do this I get " Trying to get property of non-object"

   <?php echo $profile->custom_url;?>

yet I have seen code where it's not in a foreach loop and the data displays. Can anybody help explain why that is?

Your foreach should have the format of (array_expression as $value). source

<?php foreach ($profile as $p):?>
<?php echo $p->custom_url;?>
<?php endforeach?>
// $profile is an array
<?php foreach ($profile as $profile):?>
    // inside foreach $profile is the element of the array $profile
    <?php echo $profile->custom_url;?>
<?php endforeach?>

// $profile is an array not an object
<?php echo $profile->custom_url;?>

// You'd better use another variable name for the element.
<?php foreach ($profile as $element):?>
    <?php echo $element->custom_url;?>
<?php endforeach?>