Re: optional object arguments to a function

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 13 February 2010 10:07, Jochem Maas <jochem@xxxxxxxxxxxxx> wrote:
> Op 2/13/10 8:05 AM, Michael A. Peters schreef:
>> I've started working on a class using DOMDocument to assemble MathML in
>> php. The class, assuming I actually succeed, will eventually be used for
>> parsing LaTeX math equations to MathML without the need to have TeX
>> installed. I probably won't be able to support all the possibilities for
>> equations that LaTeX does w/o a TeX install (and definitely not user
>> defined macros) but I suspect I can (hopefully) cover most of the common
>> stuff.
>>
>> One thing I don't know how to do, though, is write a function where
>> arguments are optional object.
>>
>> IE for a function to generate an integral, the limits are optional but
>> if specified must be an object (since they may be an equation
>> themselves). I want the default to be some kind of a null object so I
>> know to do nothing with it if it is null.
>>
>> With string/integer you just do
>>
>> function foo($a='',$b='',$c=false) {
>>   }
>>
>> How do I specify a default null object, or otherwise make the argument
>> argument optional?
>
> this first one doesn't work:
>
> <?
>
> class Foo
> {
>        function dobar(stdObject $o = null) { /* ... */ }
> }
>
> $e = new Foo;
> $f = new Foo;
>
> $f->dobar();                    // works
> $f->dobar($e);                  // catchable fatal
> $f->dobar((object)array());     // catchable fatal - check the error msg!?!?
>
> ?>
>
> ... but if you're able/willing to specify a user defined class then you
> have this option:
>
> <?php
>
> class Bar {}
>
> class Foo
> {
>        function dobar(Bar $o = null) { /* ... */ }
> }
>
> $b = new Bar;
> $f = new Foo;
>
> $f->dobar($b);
> $f->dobar();
>
> ?>
>
>>
>
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

Try stdClass.

If you know the class type, then that can be the type hint.

You can also use func_get_args() to read all the parameters and type
check them if there are MANY optional parameters.

-- 
-----
Richard Quadling
"Standing on the shoulders of some very clever giants!"
EE : http://www.experts-exchange.com/M_248814.html
EE4Free : http://www.experts-exchange.com/becomeAnExpert.jsp
Zend Certified Engineer : http://zend.com/zce.php?c=ZEND002498&r=213474731
ZOPA : http://uk.zopa.com/member/RQuadling

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux