程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> 怎樣使用PHP調用功能強大的JAVA類庫

怎樣使用PHP調用功能強大的JAVA類庫

編輯:PHP綜合

JAVA是個非常強大的編程利器,它的擴展庫也是非常的有用,這篇教程,主要講述怎樣使用PHP調用功能強大的JAVA 類庫(classes)。為了方便你的學習,這篇教程將包括JAVA的安裝及一些基本的例子。

windows下的安裝

第一步:安裝JDK,這是非常容易的,你只需一路回車的安裝好。然後做好以下步驟。

在 Win9x 下加入 :“PATH=%PATH%;C:\jdk1.2.2\bin” 到AUTOEXEC.BAT文件中

在 NT 下加入 “;C:\jdk1.2.2\bin”到環境變量中。

這一步是非常重要的,這樣PHP才能正確的找到需調用的JAVA類。

第二步:修改你的PHP.INI文件。

[java]
extension=php_java.dll
java.library.path=c:\web\php4\extensions\
java.class.path="c:\web\php4\extensions\jdk1.2.2\php_java.jar;c:\myclasses"
在PHP.INI中加入extension=php_java.dll

並在[java]中,設定好java.class.path,讓它指向php_java.jar,如果你使用新的JAVA類,你也應該存入這個路徑,在這篇例子中,我們使用c:\myclasses這個目錄。

第三步:測試環境,創建如下PHP文件:

<?php
$system = new Java("java.lang.System");
print "Java version=".$system->getProperty("java.version")." <br>\n";
print "Java vendor=".$system->getProperty("java.vendor")." <p>\n\n";
print "OS=".$system->getProperty("os.name")." ".
    $system->getProperty("os.version")." on ".
    $system->getProperty("os.arch")." <br>\n";
$formatter = new Java("java.text.SimpleDateFormat","EEEE,
MMMM dd, yyyy 'at' h:mm:ss a zzzz");
print $formatter->format(new Java("java.util.Date"))."\n";

?>

如果你正確安裝了,你將會看到以下信息:

Java version=1.2.2

Java vendor=Sun Microsystems Inc.

OS=Windows 95 4.10 on x86

Wednesday, October 18, 2000 at 10:22:45 AM China Standard Time

這樣,我們就已經成功的建立起了可以使用JAVA類的PHP運行環境,我們可以開始我們接下去的課程了。

例子1:創建和使用你自己的JAVA類

創建你自己的JAVA類非常容易。新建一個phptest.java文件,將它放置在你的java.class.path目錄下,文件內容如下:

public class phptest{
/**
* A sample of a class that can work with PHP
* NB: The whole class must be public to work,
* and of course the methods you wish to call
* directly.
*
* Also note that from PHP the main method
* will not be called 
*/
public String foo;
/**
* Takes a string and returns the result
* or a msg saying your string was empty
*/
public String test(String str) {
if(str.equals("")) {
    str = "Your string was empty. ";
}
return str;
}
/**
* whatisfoo() simply returns the value of the variable foo.
*/
public String whatisfoo() {
return "foo is " + foo;
}
/**
* This is called if phptest is run from the command line with
* something like
* java phptest
* or
* java phptest hello there
*/
public static void main(String args[]) {
phptest p = new phptest();

if(args.length == 0) {
String arg = "";
System.out.println(p.test(arg));
}else{
for (int i=0; i < args.length; i++) {
String arg = args[i];
System.out.println(p.test(arg));
}
}
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved