简体   繁体   中英

Should I set a variable to NULL or ' ' before defining it?

So, I have this code.

$url = "www.google.com";
<script>
    $( document ).ready(function() {
     alert(<?=$url?>);
    }); 
</script> 

Sometimes this variable will be empty depending of what section of the page is loaded. The page that should echo the url is section 2 but not section three. The jquery code is set at the footer of the page. My knowledge of php is very limited, so I am wondering if I should set the variable to null or '' so that if it is empty it is "defined?". I could use the isset, but that is not an option.

$url = '';
$url = "www.google.com";
<script>
    $( document ).ready(function() {
     alert(<?=$url?>);
    }); 
</script>

The code that loads the sections looks someting like this.

if(condition1){

} elseif(condition2){
    $url = "www.google.com";
}else{


}

Actually it looks like you don't need PHP involved at all, as you are talking about "what section of the page is loaded", so surely you could get the position on page using javascript, such as here: How to get the anchor from the URL using jQuery?

Otherwise, if the page is being built by PHP prior to output, then why can't you use isset?

$url = "www.google.com";
<script>
    $( document ).ready(function() {
     alert(<?php 
if (isset($url) && !empty($url)){ echo $url;} ?>);
    }); 
</script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM