How to Use a PHP Class from Another File

How to use a PHP class from another file?

You can use include/include_once or require/require_once

require_once('class.php');

Alternatively, use autoloading
by adding to page.php

<?php 
function my_autoloader($class) {
include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

$vars = new IUarts();
print($vars->data);
?>

It also works adding that __autoload function in a lib that you include on every file like utils.php.

There is also this post that has a nice and different approach.

Efficient PHP auto-loading and naming strategies

PHP How to call a function from another class and another file?

Your issues:

  • You CANNOT have a class named function. function is a keyword.
  • You initialize $Func, but make call using $Function

If you remove these two issues, your code will work correctly:

class ClassController{

public function test(){
echo 'this is test';
}
}

class ClassFunction{

public function testfuncton1(){
ClassController::test();
}
}

$Func = new ClassFunction();
$Func->testfuncton1();

This should print this is a test

Can I include code into a PHP class?

No. You cannot include files in the class body.

In a file defining a class, you may only include files in a method body or outside the class body.

From your description I take you want this:

<?php // MyClass.php
class MyClass
{
protected $_prop;
include 'myclass-methods.php';
}

<?php // myclass-methods.php
public function myMethod()
{
$this->$_prop = 1;
}

Running this code will result in

Parse error: syntax error, unexpected T_INCLUDE, expecting T_FUNCTION

What is possible though is this

<?php // MyClass.php
class MyClass
{
protected $_prop;
public function __construct() // or any other method
{
include 'some-functions.php';
foo($b); // echoes 'a';
}
}

<?php // some-functions.php
$b = 'a';
function foo($str)
{
echo $str;
}

Doing it this way, will import the contents of the include file into the method scope, not the class scope. You may include functions and variables in the include file, but not methods. You could but should not put entire scripts into it as well and change what the method does, e.g.

<?php // MyClass.php
// ...
public function __construct($someCondition)
{
// No No Code here
include ($someCondition === 'whatever') ? 'whatever.php' : 'default.php';
}
// ...

<?php // whatever.php
echo 'whatever';

<?php // default.php
echo 'foo';

However, patching the class this way to exhibit different behavior is not how you should do it in OOP. It's just plain wrong and should make your eyes bleed.

Since you want to dynamically change behavior, extending the class is also not a good option (see below why). What you really will want to do is write an interface and make your class use objects implementing this interface, thus making sure the appropriate methods are available. This is called a Strategy Pattern and works like this:

<?php // Meowing.php 
interface Meowing
{
public function meow();
}

Now you got the contract that all Meowing Behaviors must obey, namely having a meow method. Next define a Meowing Behavior:

<?php // RegularMeow.php
class RegularMeow implements Meowing
{
public function meow()
{
return 'meow';
}
}

Now to use it, use:

<?php // Cat.php
class Cat
{
protected $_meowing;

public function setMeowing(Meowing $meowing)
{
$this->_meowing = $meowing;
}

public function meow()
{
$this->_meowing->meow()
}
}

By adding the Meowing TypeHint to setMeowing, you make sure that the passed param implements the Meowing interface. Let's define another Meowing Behavior:

<?php // LolkatMeow.php
class LolkatMeow implements Meowing
{
public function meow()
{
return 'lolz xD';
}
}

Now, you can easily interchange behaviors like this:

<?php
require_once 'Meowing.php';
require_once 'RegularMeow.php';
require_once 'LolkatMeow.php';
require_once 'Cat.php';

$cat = new Cat;
$cat->setMeowing(new RegularMeow);
echo $cat->meow; // outputs 'meow';
// now to change the behavior
$cat->setMeowing(new LolkatMeow);
echo $cat->meow; // outputs 'lolz xD';

While you also could have solved the above with inheritance by defining an abstract BaseCat and meow method and then deriving concrete RegularCat and Lolkat classes from that, you have to consider what you want to achieve. If your cats will never change the way they meow, go ahead and use inheritance, but if your RegularCat and Lolkat is supposed to be able to do arbitrary meows, then use the Strategy pattern.

For more design patterns in PHP, check these resources:

  • http://www.php.net/manual/en/language.oop5.patterns.php
  • http://www.ibm.com/developerworks/library/os-php-designptrns/
  • http://www.fluffycat.com/PHP-Design-Patterns/
  • http://sourcemaking.com/design_patterns

PHP: calling a parent class from another file

Main.php does not need to include parent.php, as extended-classes.php already includes it. Alternatively, you can use include_once or require_once instead of include.

Include another file in PHP class

You can use include (dirname(__FILE__)."/../database.php") to access the database.php file in the account.php file

Import php class from file

include("db/models/Foo.php");

Since your db folder is inside route you can simple access it like that.

You don't need the ./ to move one step before cause your main is already in the root. You need to move inside your nested folders to reach the Foo.php

Since you did not provide the full tree i assumed that your path to Foo.php is:

C:\Users\Desktop\Code\test-project\db\models\Foo.php

Defined PHP class from another file not working

I've copied and pasted your code onto my localhost and it works fine.

Sample Image

What you have here is an issue running php scripts via whatever web server you're trying to use. Make sure you can get any php script running, such as <?php phpinfo(); ?>.

How to call class function from another file through url?

First include file1 to file2 then after call your method like.

file-2.php

<?php

use Inc\Core\CronMethods;
require_once(file1 path);

CronMethods::import();

Using Variable From Other File To Be Used Inside PHP Class

The problem with the approach you've chosen to use is that the class is no longer reusable. Any time you instantiate the Database class, it will use the global variables.

I'd be more inclined to set it up like this:

Database.php

class Database {

private $host;
private $db_name;
private $username;
private $password;

function __construct($host, $db_name, $username, $password) {
$this->host = $host;
$this->db_name = $db_name;
$this->username = $username;
$this->password = $password;
}
}

Then in the file you use the Database class:

include('../config.php');

$db = new Database($db_server, $db_name, $db_user, $db_password);


Related Topics



Leave a reply



Submit