Home php教程 php手册 PHP调用COM组件的说明

PHP调用COM组件的说明

Jun 06, 2016 am 09:51 AM
com component php code Open source programming programming language software development

在PHP 4.2.0 至 4.2.3中,可以使用w32api_register_function 函数调用外部的DLL,前提是需要在php.ini中打开扩展的php_w32api.dll。

如果使用的是PHP 5,调用DLL只有使用PHP的COM类了。

基本方法为:$obj = new COM("server.object")

下面介绍如何用PHP调用COM组件,采用的是msvs.net2005环境下的C#建立COM组件。

1. 用C#创建COM对象

COM对象是ClassLibrary类,它生成DLL文件。要在VS开发环境中创建一个简单的COM对象,我们可以依次选择“文件”->“新建”->“项目”->“Visual C#”->“类库”,然后创建一个名字为Comtest的工程。

需要注意的是:在COM中调用VC#对象需要下面的条件:

·类必须是public性质。

·特性、方法和事件必须是public性质的。

·特性和方法必须在类接口中定义。

·事件必须在事件接口中定义。

不是在这些接口中定义的public性质的类成员不能被COM访问,但它们可以被其他的.NET Framework对象访问。要让COM能够访问特性和方法,我们必须在类接口中定义它们,使它们具有DispId属性,并在类中实现这些特性和方法。这些成员定义时的顺序也就是它们在COM中顺序。要让COM访问类中的事件,必须在事件接口中定义这些事件,并赋予它们DispId属性。

在接口名字之前,每个接口需要一个GUID特性。要生成唯一的Guid,需要运行guidgen.exe工具软件,并选择“registry format”。在Program Files\Microsoft Visual Studio 2005\Common7\Tools\guidgen.exe可获得。

需要注意的是,在类的前面,需要设置下面的特性:

ClassInterface(ClassInterfaceType.None),

ComSourceInterfaces(typeof(*** _Events))

ClassInterfaceType.None表示没有为该类生成类接口,如果没有明确地实现接口,类只能通过IDispatch提供后期绑定访问。用户希望通过明确地由类实现的接口使外部对象能够访问类的功能,这也是推荐的ClassInterfaceAttribute的设置。

ComSourceInterfaces(typeof(*** _Events))确定许多作为COM事件向外部对象提供的接口。

下面是代码示例:

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.InteropServices;

using System.Reflection;

using System.Data.OleDb;

using System.Data;

using System.Collections;

using System.Collections.Specialized;

namespace Comtest

{

    //类接口

    [Guid("394BE3FE-18B8-4c5e-B611-75B5C5493A4E")]

    public interface ITest

    {

        string Test(string test);

        [DispId(1)]       //固定写法,索引号从1开始

        string About();

        [DispId(2)]

        int Add(int a, int b);

    }

 

    //事件接口

    [Guid("45875EE5-5C8D-4016-897A-FCC7DD5A6834"),             //固定写法

    InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]

    public interface ITest_Events

    {

    }

 

    //类

    [Guid("854C2016-E7BF-41ea-8F09-B873698E9F8E"),           //固定写法

     ClassInterface(ClassInterfaceType.None),

    ComSourceInterfaces(typeof(ITest_Events))]

    public class Class2 : ITest          //该类继承上面的接口,并实现抽象方法

    {

        public string Test(string test)

        {

            return test;

        }

 

        public string About() { return "欢迎访问 http://www.35.com"; }

        public int Add(int a, int b) { return a + b; }

    }

 

}

 

在创建COM对象前,我们必须向COM Interop注册该对象。右击方案管理器中的工程名字,点击快捷菜单上的“属性”选项,然后再点击“生成”选项,将“为COM Interop注册”钩上。打开AssemblyInfo.cs将comVisible设为true。

为了对程序集进行唯一的标识,安全策略和版本策略,可以为类库组合建立一个强名字。注意:不是必须。创建强名字需要用到SN.EXE名字,在“开始—VS2005 —VS Tools—VS命令提示符”,输入:

sn -k Comtest_Key.snk

将Comtest_Key.snk 添加入项目中(在Program Files\MS Visual Studio 2005\VC下),然后打开AssemblyInfo.cs,并加入下面一行的内容:

[assembly: AssemblyKeyFile("Comtest_Key.snk")]

最后生成项目,即可在bin下获得COM组件。

2. PHP调用COM组件

直接在PHP中使用COM类进行访问,即可。

代码如下:

$b=new COM("Comtest.Class2");

$t1=126;

$t2=456; 

$r=$b->add($t1,$t2);

$f=$b->about();

echo  $r;  

echo $f;

?>  

除此之外,调用访问EXCEL、WORD和数据库,都可以使用COM类。

以下为调用WORD的简单例子:

// 启动 word

$word = new COM("word.application") or die("Unable to instanciate Word");

print "Loaded Word, version {$word->Version}\n";

 

//将其置前

$word->Visible = 1;

 

//打开一个空文档

$word->Documents->Add();

 

//随便做些事情

$word->Selection->TypeText("This is a test...");

$word->Documents[1]->SaveAs("Useless test.doc");

 

//关闭 word

$word->Quit();

 

//释放对象

$word->Release();

$word = null;

?>

 

以下为访问MSSQL数据库系统的简单例子:

     //访问MSSQL数据库系统

     echo '访问MSSQL
'   ;

          $dbConn=new  COM   ("ADODB.Connection")   or   die("创建COM失败");  

          $ADO='Provider=sqloledb;Data Source=10.35.58.74;Initial Catalog=Tour;Min Pool Size=1;Persist Security Info=False;User;Password=fq15Ns@E#(';

          //"Provider=sqloledb;DataSource=10.35.58.112;Initial   Catalog=Tour;User   Id=sa;Password=sa;"; fq15Ns@E#(  

          //Access如:$ADO="DRIVER={Microsoft   Access   Driver   (*.mdb)};   DBQ="   .   realpath("mydb.mdb");    

          $dbConn->open($ADO);  

          //if($dbConn)   echo"create   conn   OK";  

          $rs=new   COM("ADODB.RecordSet")   or   die("创建RS失败");  

          echo"
";  

          //if($rs)   echo"create   rs   OK";  

          $sql="Exec P_SelUser 9001111";//"SELECT   *   FROM   user_userInfo";  

          $rs->open($sql,$dbConn,1,1);  

         

          while(!$rs->eof){  

   

                  echo   $rs->fields["Account"]->value.":";  

                  echo   $rs->fields["PhoneID"]->value;  

                  echo"
";  

   

                  $rs->movenext();  

          }  

   

          $rs->Close;  

          $rs=null;  

   

          $dbConn->Close;  

          $dbConn=null;  

  ?>  

这说明如果我们要使用PHP访问MSSQL,可以通过调用COM组件来实现。

 

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Demystifying C: A Clear and Simple Path for New Programmers Demystifying C: A Clear and Simple Path for New Programmers Oct 11, 2024 pm 10:47 PM

C is an ideal choice for beginners to learn system programming. It contains the following components: header files, functions and main functions. A simple C program that can print "HelloWorld" needs a header file containing the standard input/output function declaration and uses the printf function in the main function to print. C programs can be compiled and run by using the GCC compiler. After you master the basics, you can move on to topics such as data types, functions, arrays, and file handling to become a proficient C programmer.

See all articles