Example 1: it is very easy to create and use your own JAVA class. Create a phptest. java file, place it in your java. class. in the path Directory, the file content is as follows: publicclassphptest & #123; *** AsampleofaclassthatcanworkwithPHP * NB: Thewho Example 1: Create and use your own JAVA class
It is very easy to create your own JAVA class. Create a new phptest. java file and place it in your java. class. path Directory. the file content is as follows:
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
* 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 ));
}
}
}
}
After creating this file, we need to compile this file and use the javac phptest. java command in the doscommand line.
To test this JAVA class using PHP, we create a phptest. PHP file with the following content:
$ Myj = new Java ("phptest ");
Echo "Test Results are
". $ Myj-> test (" Hello World ")."";
$ Myj-> foo = "A String Value ";
Echo "You have set foo
". $ Myj-> foo ."
N ";
Echo "My java method reports:
". $ Myj-> whatisfoo ()."
N ";
?>
If you get the warning: java. lang. ClassNotFoundException error, it means that your phptest. class file is not in your java. class. path Directory.
Note that JAVA is a forced type language, but PHP is not. in this way, errors are easily caused when we integrate them. Therefore, when we pass variables to JAVA, you must specify the variable type correctly. For example: $ myj-> foo = (string) 12345678; or $ myj-> foo = "12345678 ";
This is just a small example. you can create your own JAVA class and use PHP to call it very well!