1

Code example;

PHP Web Page: (index.php)

 <html><head></head>
    <body>
    <?php 
    include("class_validation.php");
    $val = new validation();

        if(isset($_POST['action'])) doSomething();

    function doSomething() {
        $val->validate(); //I AM UNABLE TO DO THIS!
    }
    ?>
    </body>
    </html>

PHP file: (class_validation.php)

<?php
class validation()
{
    function validate(){
        //some validation
    }
}
?>

QUESTION: How can I call a function from the 'class_validation.php' file in a function I created in my PHP web page? I can correctly call the function doSomething() as well as call the function $val->validate(); when not located in another function. I there a way to do this?

2 Answers 2

3

$val is out of scope in that doSomething() function call. Pass it as a parameter to the function:

// Define the function to accept a parameter. Use a type hint to be sure it is 
// a validation object
function doSomething(validation $val) {
  $val->validate(); 
}

if(isset($_POST['action'])) doSomething($val);

(PHP documentation on type hinting)

Alternatively, and not recommended, you may use the global keyword inside the function to reference the global $val.

function doSomething() {
  // Don't do it this way. The func parameter is preferred
  global $val;
  $val->validate(); 
}
Sign up to request clarification or add additional context in comments.

Comments

0

You seems to be looking for closure support, which are only available for anonymous functions.

And according to your code sample, it doesn't seems to be a right use case. Maybe you should just pass this value as function parameter ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.