rmap
rmap

Reputation: 65

PHP classses/functions

I am just getting into PHP classes (OK it took me years ...... ) but n the past I have alsways relied on "hard multiple php/sql" coding and the odd function. Now I see the "wisdom etc. of classes. but a bit of help please. A lot of my functions would use a common repeat function for extracting function $args.

OK there is func_get_args(), but all my args are a bit like this (assuming a function called testfunction :) :

testfunction('title=this','li=no','abc=yes');   

How is the best way to create a common function that can be used in many other functions that basically does (below) this (but don't worry about the echo $a[0].' -'. $a[1]; line that is just there for me to see what happens.

function args($args){
    $args = func_get_args();
    foreach ($args as $key=>$val) {
        $a = explode('=',$val);
        echo $a[0].' -'. $a[1];
    }
}

In other words say I have 2 - 5 - 20 different functions all with $args of some description (I would know what the args were though) how do you create function args() that can be used inside all the other args therey saving "lines" of code.

Your help/answers much appreciated

Upvotes: 0

Views: 62

Answers (1)

Álvaro González
Álvaro González

Reputation: 146460

The key point of object-oriented programming is that you create classes and methods that match your data model and business logic. You don't give any clue about it so it's impossible to suggest a proper design. However, I'll assume that you just want some generic tips about how to reuse a function that does some string manipulations.

If the function is to be reused in related pieces of code, you can write a base class with common features and several child classes that inherit from it:

<?php
class Base{
    public function args(){
    }
}
class Foo extends Base{
}
class Far extends Base{
}
?>

Now, any instance of Foo or Bar has a args() method available:

<?php
$a = new Foo;
$a->args();
$b = new Bar;
$b->args();   
?>

If the function is to be reused in unrelated pieces of code, you can write a class to encapsulate the reusable functionality:

Now, you can do StringUtils::args() anywhere you need it.

Upvotes: 1

Related Questions