0

Code example:

<?php // class_database.php
class database
{
include("class_validation.php"); //this does not work
$val = new validation() //this does not work
    public function login($value)
    {
if($val->validate($value))
{
//do something
}
    }
}

<?php // class_validation.php
class validation
{
    public function validate($value)
    {
if($value > 50) return true;
return false;
    }
}

How do I delegate the class validation in class database? I do not wish to inherit (implement or extends) the class validation -> behavior in validation is not to be changed. I just want to use the methods from validation class. Any OOP solutions? Thanks in advance

1
  • 1
    Just like your question yesterday, $val will not be in scope in public function login(). You need to define $val inside the function, or as a class property and access via $this->val in the function. Commented Nov 16, 2012 at 14:17

3 Answers 3

2

You cant use include inside a class like that! Either include it at the beginning of the file ( my suggestion ) or use it one line before $val = new validation(); call.

class_database.php:

<?php
    include("class_validation.php");

    class database
    {
        public function login($value)
        {
            $val = new validation();
            if($val->validate($value))
            {
                //do something
            }
        }
    }
?>

  class_validation.php:

<?php
    class validation
    {
        public function validate($value)
        {
            if($value > 50)
                return true;

            return false;
        }
    }
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Bonus points for spotting the missing semi colon on $val = new validation()
I tried this before but didn't work. Tried it again and succeeded. Guess I did something wrong before. Thanks!
0

You need to move the include outside the class. PHP does not allow classes within classes.

Try something like this :

Code example:

<?php 
include("class_validation.php"); // include outside the class declaration
// class_database.php
class database
{

$val = new validation()
    public function login($value)
    {
if($val->validate($value))
{
//do something
}
    }
}

Comments

0

You can either put the include() outside your class (at the top of your page, class_database.php), or if your using a framework/autoloader you can call it by namespace:

Option 1

<?php
include('class_validation.php');
class database {

}

Option 2

namespace ThisCoolThing;
use \OtherCoolThing\validation;

class database { ... }

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.