Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP custom function scope / good practice

Tags:

php

I have script which has the following structure:

<?php
    if( a == b ){

        function some_function_name(){
            // do something here
        }

        if( c == d ){
            some_function_name();
        }
    }
?>

I get an error message saying that some_function_name(); does not exist.

What am I doing wrong and is this good practice?

I want to create a function, because I have a bunch of steps which I need to use many times, and I would prefer not to have to copy/paste the same code over and over again.

like image 908
oshirowanen Avatar asked Apr 26 '26 10:04

oshirowanen


2 Answers

You can not declare function in if-statements.

you could do this:

<?php   
    function some_function_name() {
       // do something here
    }

    if( a == b  && c == d ) {
        some_function_name();
    }
?>
like image 137
peko Avatar answered Apr 29 '26 00:04

peko


I would avoid defining the function inside a conditional if() statement. Define the function first, at the top of the file and call it when necessary.

like image 45
Michael Berkowski Avatar answered Apr 29 '26 02:04

Michael Berkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!