Red Virus
Red Virus

Reputation: 1707

Overriding a functions default values

I' am trying to override a function defaults values so that I can customize the function. Here's whats happening currently.

The order in which the script loads

<?php require(  dirname(__FILE__) . "/filters.php" ); ?>
<?php require(  themes_path . "/2014/functions.php" ); ?>

filter.php

This is the original function

/* Login Page */
if( !function_exists ("customize_login" ) ){
    function customize_login( $args = array() ){
        $defaults = array(
            "image_url" => bs_url . "/system/bootstrap/images/logo.png",
            "image_alt" => "Original ALT",
            "image_title" => "Original Title",
            "image_class" => "profile-img"
        );          
        $args = array_merge( $defaults, $args);
        return $args;
    }
}

functions.php

I' am overriding the above function here

/* Override the Login Page */
    $args = array(
        "image_alt" => "Override ALT",
        "image_title" => "Override Title",
        "image_class" => "profile-img"
    );
    call_user_func( "customize_login", $args );

login.php

Here is where I want to use the function which I have override on functions.php file

$customize_login = customize_login();
  if( is_array( $customize_login ) ){
    $image_url = $customize_login["image_url"];
    $image_alt = $customize_login["image_alt"];
    $image_title = $customize_login["image_title"];
    $image_class = $customize_login["image_class"];
 }

The Problem?

I still get the original function values and NOT the override function values. How can I access the override function values?

Upvotes: 0

Views: 93

Answers (1)

dognose
dognose

Reputation: 20899

You don't need to call the method customize_login somewhere with your override, you need to call it with your override, when you require the values to be overwritten:

$args = array(
    "image_alt" => "Override ALT",
    "image_title" => "Override Title",
    "image_class" => "profile-img"
);

$customize_login = customize_login($args);
  if( is_array( $customize_login ) ){
    $image_url = $customize_login["image_url"];
    $image_alt = $customize_login["image_alt"];
    $image_title = $customize_login["image_title"];
    $image_class = $customize_login["image_class"];
 }

Just noted, that there is a conditional check arround customize_login() to see, if the function is already defined or not.

So, you should be able to replace the whole function by declaring it earlier from within your own code. Provide:

function customize_login($args){
       $myDefaults = array(
        "image_alt" => "Override ALT",
        "image_title" => "Override Title",
        "image_class" => "profile-img"
    );
    $args = array_merge( $myDefaults, $args);
    return $args;
}

somewhere earlier and the original function will never be defined, but every call providing additional args - maybe from within the framework - will work as expected.

Upvotes: 2

Related Questions