2017-05-02 5 views
0

으로 삼항 연산자를 포함 할 수 없습니다 echo 성명 :여기에 echo 문

echo " <a class=\"pagination-link\" href='{$_SERVER['PATH_INFO']}?page=$nextpage#comment-target'> &gt; </a> "; 

그리고 여기 ternary expression됩니다. 그것이 무엇을하는 조건이 true 인 경우에만 링크의 끝에 #comment-target을 연결할 수 있습니다 :

($paginationAddCommentAnchor ?? null) ? '#comment-target' : null 

것은 내가 ternary expression함으로써 echo 성명에서 #comment-target를 교체해야하지만, 모든 시도는 못생긴 볼로 끝 잘못된 견적과 함께 진흙의. 예 시도 : 최종 결과가 초기 echo 문장과 동일하지만, 삼항로 제작 있도록

echo " <a class=\"pagination-link\" href='{$_SERVER['PATH_INFO']}?page=$nextpage . ($paginationAddCommentAnchor ?? null) ? '#comment-target' : null'> &gt; </a> "; 

은 무엇 적절한 구문 것입니까?

+0

'$ paginationAddCommentAnchor ?? null'은'$ paginationAddCommentAnchor'와 동일합니다 – axiac

+0

여러 줄과 변수를 사용하면 코드를 훨씬 쉽게 읽을 수 있습니다. – Quentin

+1

PHP는 큰 따옴표 (''')로 묶인 문자열에서 [variables parsing] (http://php.net/manual/en/language.types.string.php#language.types.string.parsing) 표현식을 평가할 필요가 있다면 문자열 외부에 넣고 [문자열 결합 연산자 ('.')] (http://php.net/manual/en)를 사용하여 그 값을 주변 문자열과 연결해야합니다. /nlanguage.operators.string.php) – axiac

답변

0

PHP는 variables parsing 문자열을 큰 따옴표 (")로 묶었지만 그게 전부입니다. 표현식을 평가해야하는 경우 문자열 외부에 넣고 그 값을 string concatenation operator (.)을 사용하여 주변 문자열과 연결해야합니다.

또는 더 많은 읽을 수있는 코드를 얻기 위해 사용 printf() :

printf(' <a class="pagination-link" href="%s?page=%s%s> &gt; </a> ', 
    $_SERVER['PATH_INFO'], $nextpage, 
    $paginationAddCommentAnchor ? '#comment-target' : '' 
); 
+0

감사합니다. 도움이되었습니다. 답변으로 선택하겠습니다. 나는 당신이 말한 바대로 변수를 외부에 생성 한 다음 간단히 그것을 합쳤습니다. –

0

은 한 줄에 많은 것들을 올바르게 모든 부분 (따옴표, 문자열 conncatenation을 제어하지, 삼항 연산자를 시도하는 것 같은데 ...). 분리 된 블록의 마지막 문자열을 구축, 투명하고 통제하게 유지하려면

$tmp_str = $nextpage . ($paginationAddCommentAnchor ?? null) ? '#comment-target' : ''; 

echo "<a class=\"pagination-link\" href=\"{$_SERVER['PATH_INFO']}?page=$tmp_str\"></a>"; 

시험이 here.