2011-07-09 53 views
1

,能夠通過在從取內的實例化的對象類的範圍PHP變量的引用PHP OOP類(從單獨的PHP文件)外傳遞PHP變量到HTML 標籤的節點值(PHP)插入到JQuery函數中,以便呈現給一個數字或字符串來顯示添加的項目數量?我這裏有一個代碼是這樣的:在JQuery的功能

<!--in cart.php--> 
$(document).ready(function() { 
    $('div#cart').replaceWith('<div id=\'cart2\'><span><?php echo ('.**$itemcount**.'); ?> </span> <a href=\'viewcart.html\' class=\'view-cart\'>View Cart</a><a class=\'checkout\' href=\'checkout.html\'>Checkout</a></div>'); 
}); 

其中$itemcount在PHP外部文件存儲的變量稱爲store.php

尋求幫助非常感謝!

回答

0

一個有趣的問題,至少可以說...

比方說store.php看起來是這樣的:

<?php 
class store { 
    private $_itemcount = 0; 
    public function getItemCount(){ 

     return $this->_itemcount; 

    } 
} 
?> 

從那裏,我們再這樣下去在cart.php:

<?php 
    $store = new store(); 
    $itemcount = $store->getItemCount(); 

    echo <<<html 
    $(document).ready(function() { 
     $('div#cart').replaceWith("<div id='cart2'><span>$itemcount</span><a href='viewcart.html' class='view-cart'>View Cart</a><a class='checkout' href='checkout.html'>Checkout</a></div>"); 
    }); 
html; 
?> 

這樣,我們可以返回值並在javascript中使用它。

0

store.php

<?php $itemcount = 10; ?> 

在cart.php

$(document).ready(function() { 
    $('div#cart').replaceWith('<div id=\'cart2\'><span><?php require 'store.php'; echo $itemcount; ?> </span> <a href=\'viewcart.html\' class=\'view-cart\'>View Cart</a><a class=\'checkout\' href=\'checkout.html\'>Checkout</a></div>'); 
}); 
0

有一些答案在這裏,將與一個字符串或數字的工作,但如果您的需求開發任何你更多的複雜性會遇到問題。

如果需要的話可以序列PHP對象爲JSON,這將允許您創建一個可以直接由JavaScript/jQuery代碼中使用的JavaScript對象。

假設你cart.php腳本有從store.php訪問對象由$的PHPObject表示:

例如

... 
$(document).ready(function() { 
    var jsPhpObject = <?php echo json_encode($phpObject); ?>; // doesn't need to be inside document.ready if required elsewhere 
    $('div#cart').replaceWith("<div id='cart2'><span>" + jsPhpObject.property + "</span><a href='viewcart.html' class='view-cart'>View Cart</a><a class='checkout' href='checkout.html'>Checkout</a></div>"); 
}); 
... 
0

store.php

<?PHP 
class SomeClass 
{ 
    public $insideMemberNum; 

    public function __construct() 
    { 
     global $outsideNum; 
     $insideNum = 2; 
     $this->insideMemberNum = 2; 

     // 1. $outsideNum = $insideNum; (this will make $outsideNum = 2, even outside this class) 
     // 2. $outsideNum = &$insideNum; (this will make $outsideNum = 2, but only wihtin this scope, after it will go back to 1) 

     // so youre options are... 
     // 1. pass by value 
     // 2. create a public variable and store the number in there 
     // 3. create a private variable and a public function to return the value of that variable like someone else suggested 
    } 
} 
?> 

incart.php

<?PHP 


$outsideNum = 1; 
echo $outsideNum . "<br />"; // prints out 1 

include("store.php"); // include the external file 
$obj = new SomeClass(); // instansiate the object 


echo $outsideNum . "<br />"; // option 1 prints out 2, option 2 prints out 1 
echo $obj->insideMemberNum . "<br />"; // prints out 2 

?>