How to Include Code into a PHP Class

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

How to include a class in PHP

Your code should be something like

require_once('class.twitter.php');

$t = new twitter;
$t->username = 'user';
$t->password = 'password';

$data = $t->publicTimeline();

Add code snippet into a class

Try this class you're doing in a wrong way.

session_start();    
class Shopping {


public function __construct()
{

}

//get cart products
public function getCartProducts()
{
$cart = array();
if(isset($_SESSION['cart'])) {

$cart = unserialize($_SESSION['cart']);
}
return $cart;
}

//add product to cart
public function addToCart($product_details)
{
$cart = $this->getCartProducts();
$product_id = $product_details['product_id'];
$is_quantity = $this->addQuantity($product_id); //check if product already exists in session if then increase the quantity
if(!$is_quantity) {
$product_details = array(
'qty' => $product_details['qty'],
'price' => $product_details['price'],
'product_name' => $product_details['name'],
'product_id' => $product_id
);
array_push($cart, $product_details);
$_SESSION['cart'] = serialize($cart);
}
}

//add quantity if product already exists
private function addQuantity($product_id)
{

$cart = $this->getCartProducts();
$i = 0;
foreach ($cart as $product) {
if($product['product_id'] == $product_id)
{
$product['qty'] += 1;
$cart[$i] = $product;
$_SESSION['cart'] = serialize($cart);
return true;
}
$i++;
}
return false;
}

public function clearCart()
{
unset($_SESSION['cart']);
}

public function removeProduct($product_id)
{
$cart = $this->getCartProducts();
$new_cart = array();
foreach ($cart as $product) {
if($product['product_id'] != $product_id)
array_push($new_cart, $product);
}
$_SESSION['cart'] = serialize($new_cart);
}
}

$shop = new Shopping();
$shop->addToCart(array('product_id'=>1,'name'=>'test 1','price'=>'120.00','qty'=>1));
$shop->addToCart(array('product_id'=>3,'name'=>'test 2','price'=>'120.00','qty'=>1));

PHP - how to include a php class file and execute a function

The urlinfo.php script was intended to be ran via PHP command line interface and expects arguments passed on via cli.

If you remove the following portion of the code:

if (count($argv) < 4) {
echo "Usage: $argv[0] ACCESS_KEY_ID SECRET_ACCESS_KEY site\n";
exit(-1);
}
else {
$accessKeyId = $argv[1];
$secretAccessKey = $argv[2];
$site = $argv[3];
}

And then do:

$accessKeyId = "youkeyid";
$secretAccessKey = "yoursecret";
$site = "yoursite";

include('urlinfo.php');

It will work as expected.

Where to place include statements in a PHP class file

I prefer it on top, the same convention as for #import/import/using in c/java/c# as it immediately lets you know what other classes your class is depending on.

You may also want to check out require_once() instead of include_once() as it will halt with an error instead of giving a warning when the included file contains an error. But of course that depends on what kind of file you're including and how critical you deem it to be.

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

injecting codes (methods) into class?

The error originates in the code you have shown as /* some code*/ in your example.

You assign an anonymous function here:

$c->customFunction['first'] = function (){ /* some code*/ };

And it remains just a function. It doesn't become a real method of the class. So using $this within it won't work.


Workaround: Pass your custom functions an $obj parameter, and have them use that instead of $this. (Really, just a quirky workaround; but doable.)

call_user_func($this->customFunction[$name], $obj=$this);

Or try classkit_method_add or runkit for a "proper" solution. - If available in your PHP.



Related Topics



Leave a reply



Submit