phpc++php-extensionphp-cpp

Convert a Php::Object back to a C++ object in PHP-CPP?


I was trying to make a Bencode extension for PHP by PHP-CPP, so there were several classes like:

class BItem : public Php::Base {
public:
virtual std::string getType() const {
    return "BItem";
}
};

class BDict : public BItem {
public:
std::unordered_map<std::string, BItem*> BData;

std::string getType() const {
    return "BDict";
}

Php::Value getItem(Php::Parameters &params) {
    std::string key = params[0];
    ...
    ...
    return Php::Object(...);
}

// PHP: $a = new BDict(); $b = new BDict(); $a->addItem($b);
void addItem(Php::Parameters &params) {
    std::string key = params[0];

    /**
     * Here's the part confusing me
     * Is there something like:
     */
    BItem *toInsert = &params[1]; // However, params[1] is actually a Php::Object
    BData.insert({key, toInsert});
}
};

class BStr : public BItem {...};
class BList : public BItem {...};
class BInt : public BItem {...};

All the types except BItem can be inserted to a BDict.

So after creating an instance of one of them, how can I pass it back to the C++ part, "convert" it back to a C++ object and finally insert it into the BData?

I'm new to php extensions and any help or hint would be greatly appreciated.


Solution

  • According to Emiel's answer

    void myFunction(Php::Parameters &params)
    {
        // store the first parameter in a variable
        Php::Value object = params[0];
    
        // we want to be 100% sure that the passed in parameter is indeed one of our own objects
        if (!object.instanceOf("MySpecialClass")) throw Php::Exception("Wrong parameter passed");
    
        // cast the PHP object back into a C++ class
        MySpecialClass *cppobject = (MySpecialClass *)object.implementation();
    
        // @todo add your own code
    }