728x90

(PHP 4, PHP 5, PHP 7)

get_class — 객체의 클래스명을 반환

설명 ¶

string get_class ([ object $object ] )

주어진 object의 클래스명을 얻습니다.

인수 ¶

object

확인할 객체

반환값 ¶

object 인스턴스의 클래스명을 반환합니다. object가 객체가 아니면 FALSE를 반환합니다.

변경점 ¶

버전설명
5.0.0부터클래스명을 원 문자대로 반환합니다.
5.0.0부터객체 메쏘드에서 호출할 때, object 인수는 선택적입니다.

예제 ¶

Example #1 get_class() 사용하기

<?php

class foo {
    function 
name()
    {
        echo 
"My name is " get_class($this) , "\n";
    }
}

// 객체 만들기
$bar = new foo();

// 외부 호출
echo "Its name is " get_class($bar) , "\n";

// 내부 호출
$bar->name();

?>

위 예제의 출력:

Its name is foo
My name is foo

Example #2 슈퍼클래스에서 get_class() 사용하기

<?php

abstract class bar {
    public function 
__construct()
    {
        
var_dump(get_class($this));
        
var_dump(get_class());
    }
}

class 
foo extends bar {
}

new 
foo;

?>

위 예제의 출력:

string(3) "foo"
string(3) "bar"

참고 ¶

add a note add a note

User Contributed Notes 35 notes

jjanak at webperfection dot net ¶
3 years ago
>= 5.5

::class
fully qualified class name, instead of get_class

<?php
namespace my\library\mvc;

class 
Dispatcher {}

print 
Dispatcher::class; // FQN == my\library\mvc\Dispatcher

$disp = new Dispatcher;

print 
$disp::class; // parse error
mail dot temc at gmail dot com ¶
6 years ago
People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance. 

Here's a good example that should fix that for ever: 

<?php 

class Foo 
function 
doMethod(){ 
  echo 
__METHOD__ "\n"

function 
doGetClassThis(){ 
  echo 
get_class($this).'::doThat' "\n"

function 
doGetClass(){ 
  echo 
get_class().'::doThat' "\n"



class 
Bar extends Foo 



class 
Quux extends Bar 
function 
doMethod(){ 
  echo 
__METHOD__ "\n"

function 
doGetClassThis(){ 
  echo 
get_class($this).'::doThat' "\n"

function 
doGetClass(){ 
  echo 
get_class().'::doThat' "\n"



$foo = new Foo(); 
$bar = new Bar(); 
$quux = new Quux(); 

echo 
"\n--doMethod--\n"

$foo->doMethod(); 
$bar->doMethod(); 
$quux->doMethod(); 

echo 
"\n--doGetClassThis--\n"

$foo->doGetClassThis(); 
$bar->doGetClassThis(); 
$quux->doGetClassThis(); 

echo 
"\n--doGetClass--\n"

$foo->doGetClass(); 
$bar->doGetClass(); 
$quux->doGetClass(); 

?> 

OUTPUT: 

--doMethod-- 
Foo::doMethod 
Foo::doMethod 
Quux::doMethod 

--doGetClassThis-- 
Foo::doThat 
Bar::doThat 
Quux::doThat 

--doGetClass-- 
Foo::doThat 
Foo::doThat 
Quux::doThat
dave at shax dot com ¶
4 years ago
A lot of people in other comments wanting to get the classname without the namespace. Some weird suggestions of code to do that - not what I would've written! So wanted to add my own way.

<?php
function get_class_name($classname)
{
    if (
$pos strrpos($classname'\\')) return substr($classname$pos 1);
    return 
$pos;
}
?>

Also did some quick benchmarking, and strrpos() was the fastest too. Micro-optimisations = macro optimisations!

39.0954 ms - preg_match()
28.6305 ms - explode() + end()
20.3314 ms - strrpos()

(For reference, here's the debug code used. c() is a benchmarking function that runs each closure run 10,000 times.)

<?php
c
(
    function(
$class 'a\b\C') {
        if (
preg_match('/\\\\([\w]+)$/'$class$matches)) return $matches[1];
        return 
$class;
    },
    function(
$class 'a\b\C') {
        
$bits explode('\\'$class);
        return 
end($bits);
    },
    function(
$class 'a\b\C') {
        if (
$pos strrpos($class'\\')) return substr($class$pos 1);
        return 
$pos;
    }
);
?>
macnimble at gmail dot com ¶
6 years ago
Need a quick way to parse the name of a class when it's namespaced? Try this:

<?php
namespace Engine;
function 
parse_classname ($name)
{
  return array(
    
'namespace' => array_slice(explode('\\'$name), 0, -1),
    
'classname' => join(''array_slice(explode('\\'$name), -1)),
  );
}
final class 
Kernel
{
  final public function 
__construct ()
  {
    echo 
'<pre>'print_r(parse_classname(__CLASS__),1), '</pre>';
    
// Or this for a one-line method to get just the classname:
    // echo join('', array_slice(explode('\\', __CLASS__), -1));
  
}
}
new 
Kernel();
?>

Outputs:
Array
(
    [namespace] => Array
        (
            [0] => Engine
        )

    [classname] => Kernel
)
var23rav at gmail dot com ¶
3 years ago
class A
{
function __construct(){
        //parent::__construct();
        echo $this->m =  'From constructor A: '.get_class();
        echo $this->m =  'From constructor A:- argument = $this: '.get_class($this);
        
        echo $this->m =  'From constructor A-parent: '.get_parent_class();
        echo $this->m =  'From constructor A-parent:- argument =  $this: '.get_parent_class($this);
    }
}
class B extends A
{
function __construct(){
        parent::__construct();
        echo $this->m =  'From constructor B: '.get_class();
        echo $this->m =  'From constructor B:- argument =  $this: '.get_class($this);
        
        echo $this->m =  'From constructor B-parent: '.get_parent_class();
        echo $this->m =  'From constructor B-parent:- argument =  $this: '.get_parent_class($this);
    }
}
$b = new B();
//----------------output--------------------

From constructor A: A
From constructor A:- argument = $this: B
From constructor A-parent: 
From constructor A-parent:- argument = $this: A
From constructor B: B
From constructor B:- argument = $this: B
From constructor B-parent: A
From constructor B-parent:- argument = $this: A

Use get_class() to get the name of class  ,it will help you get the class name, in case you extend that class with another class and want to get the name of the class to which object is instance of user get_class($object)

when you create an object of class{$b object of B} which has a super class{Class A}. 
uses these code IN Super Class {A} 
--------------------------------------------
to get class name B{object instance} :  get_class($this)  
to get class name A{super class}  : get_class() or get_parent_class($this)
Edward ¶
9 years ago
The code in my previous comment was not completely correct. I think this one is. 

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;

    protected function __construct() {
    }
    
    abstract protected function init();
    
    /**
     * Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
     * If one does exist, then the existing instance is returned.
     */
    public static function getInstance() {
        static $instance;
        
        $class = self::getClass();
        
        if ($instance === null) {
            $instance = new $class();
            $instance->init();
        }
        
        return $instance;
    }
    
    /**
     * Returns the classname of the child class extending this class
     *
     * @return string The class name
     */
    private static function getClass() {
        $implementing_class = static::$__CLASS__;
        $original_class = __CLASS__;

        if ($implementing_class === $original_class) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }
        
        return $implementing_class;
    }
}
?>
ovidiu.bute [at] gmail.com ¶
8 years ago
If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex: 

namespace Shop; 

<?php 
class Foo 

  public function 
__construct() 
  { 
     echo 
"Foo"
  } 


//Different file 

include('inc/Shop.class.php'); 

$test = new Shop\Foo(); 
echo 
get_class($test);//returns Shop\Foo 
?>
me at nwhiting dot com ¶
7 years ago
Method for pulling the name of a class with namespaces pre-stripped.

<?php
/**
* Returns the name of a class using get_class with the namespaces stripped.
* This will not work inside a class scope as get_class() a workaround for
* that is using get_class_name(get_class());
*
* @param  object|string  $object  Object or Class Name to retrieve name

* @return  string  Name of class with namespaces stripped
*/
function get_class_name($object null)
{
    if (!
is_object($object) && !is_string($object)) {
        return 
false;
    }
    
    
$class explode('\\', (is_string($object) ? $object get_class($object)));
    return 
$class[count($class) - 1];
}
?>

And for everyone for Unit Test goodiness!

<?php
namespace testme\here;

class 
TestClass {
    
    public function 
test()
    {
       return 
get_class_name(get_class());
    }
}

class 
GetClassNameTest extends \PHPUnit_Framework_TestCase
{
    public function 
testGetClassName()
    {
        
$class  = new TestClass();
        
$std  = new \stdClass();
        
$this->assertEquals('TestClass'get_class_name($class));
        
$this->assertEquals('stdClass'get_class_name($std));
        
$this->assertEquals('Test'get_class_name('Test'));
        
$this->assertFalse(get_class_name(null));
        
$this->assertFalse(get_class_name(array()));
        
$this->assertEquals('TestClass'$class->test());
    }
}
?>
janci ¶
10 years ago
To yicheng zero-four at gmail dot com: Another, maybe better example where finding out the real class (not the class we are in) in static method should be quite usefull is the Singleton pattern. 

There is currently no way how to create an abstract Singleton class that could be used just by extending it without the need to change the extended class. Consider this example:
<?php
abstract class Singleton
{
    protected static 
$__instance false;
        
    public static function 
getInstance()
    {    
        if (
self::$__instance == false)
        {
            
// This acctually is not what we want, $class will always be 'Singleton' :(
            
$class get_class();
            
self::$__instance = new $class();            
        }
        return 
self::$__instance;
    }
}

class 
Foo extends Singleton
{
    
// ...
}

$single_foo Foo::getInstance();
?>
This piece of code will result in a fatal error saying: Cannot instantiate abstract class Singleton in ... on line 11

The best way I figured out how to avoid this requires simple but still a change of the extended (Foo) class:
<?php
abstract class Singleton
{
    protected static 
$__instance false;
        
    protected static function 
getInstance($class)
    {    
        if (
self::$__instance == false)
        {
            if (
class_exists($class))
            {
                
self::$__instance = new $class();            
            }
            else 
            {
                throw new 
Exception('Cannot instantiate undefined class [' $class ']'1);
            }
        }
        return 
self::$__instance;
    }
}

class 
Foo extends Singleton
{
    
// You have to overload the getInstance method in each extended class:
    
public static function getInstance()
    {
        return 
parent::getInstance(get_class());
    }
}

$single_foo Foo::getInstance();
?>

This is of course nothing horrible, you will propably need to change something in the extended class anyway (at least the constructor access), but still... it is just not as nice as it possibly could be ;)
emmanuel dot antico at gmail dot com ¶
4 years ago
/**
* Obtains an object class name without namespaces
*/
function get_real_class($obj) {
    $classname = get_class($obj);

    if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
        $classname = $matches[1];
    }

    return $classname;
}
Frederik Krautwald ¶
10 years ago
Due to PHP 5 engine that permits to get final class in a static called function, and this is a modified version of examples published below.

<?php
abstract class Singleton {
    protected static 
$_instances = array();
   
    protected function 
__construct() {}
   
    protected static function 
getInstance() {
        
$bt debug_backtrace();
        
$class $bt[count($bt) - 1]['class'];
        if (!isset(
self::$_instances[$class])) {
            
self::$_instances[$class] = new $class();
        }
        return 
self::$_instances[$class];
    }
}
class 
extends Singleton {
    public static function 
getInstance() {
        return 
parent::getInstance();
    }
}
class 
extends Singleton {
    public static function 
getInstance() {
        return 
parent::getInstance();
    }
}
class 
extends {
    public static function 
getInstance() {
        return 
parent::getInstance();
    }
}

$a A::getInstance();
$b B::getInstance();
$c C::getInstance();

echo 
"\$a is a " get_class($a) . "<br />";
echo 
"\$b is a " get_class($b) . "<br />";
echo 
"\$c is a " get_class($c) . "<br />";
?>

I don't know about if performance would increase if debug_backtrace() is skipped and instead have getInstance() to accept a passed class retrieved by get_class() method as parameter as described in a post below.

By having set getInstance() to protected in the Singleton class, the function is required to be overridden (good OOP practice).

One thing to mention is, that there is no error checking in case $class is null or undefined, which would result in a fatal error. At the moment, though, I can't see how it could happen when the getInstance() is protected, i.e. has to be overridden in a subclass -- but with good coding practice you should always error check.
mightye at gmail dot com ¶
10 years ago
To: Bryan

In this model it is still workable if your singleton variable is actually an array.  Consider:
<?php
abstract class Singleton {
    protected final static 
$instances = array();
    
    protected 
__construct(){}
    
    protected function 
getInstance() {
        
$class get_real_class(); // imaginary function returning the final class name, not the class the code executes from
        
if (!isset(self::$instances[$class])) {
            
self::$instances[$class] = new $class();
        }
        return 
self::$instances[$class];
    }
}
class 
extends Singleton {
}
class 
extends Singleton {
}

$a A::getInstance();
$b B::getInstance();

echo 
"\$a is a " get_class($a) . "<br />";
echo 
"\$b is a " get_class($b) . "<br />";
?>
This would output:
$a is a A
$b is a B

The only alternative as described elsewhere is to make getInstance() protected abstract, accept the class name as an argument, and extend this call with a public final method for every sub-class which uses get_class() in its local object scope and passes it to the superclass.

Or else create a singleton factory like this:
<?php
final class SingletonFactory {
    protected static 
$instances = array();
    
    protected 
getInstance($class) {
        if (!isset(
self::$instances[$class])) {
            
self::$instances[$class] = new $class();
        }
        return 
self::$instances[$class];
    }
}
?>
The downside to this of course to this latter model is that the class itself doesn't get to decide if it is a singleton, the calling code gets to decide this instead, and a class that really wants or *needs* to be a singleton has no way to enforce this, not even by making its constructor protected.

Basically these design patterns, and various other meta manipulations (things which operate on the nature of the object, not on the data the object holds) could benefit greatly from knowing exactly what the final type of this object is, and not having native access to this information obligates work-arounds.
Nanhe Kumar ¶
4 years ago
<?php
class Parent{
}
class 
Child extends Parent{    
}
$c = new Child();
echo 
get_class($c//Child
?>
<?php
class Parent{
  public function 
getClass(){
     echo 
get_class(); 
  }
}
class 
Child extends Parent{
}
$obj = new Child();
$obj->getClass(); //outputs Parent
?>
<?php
class Parent{
  public function 
getClass(){
     echo 
get_class($this); 
  }
}
class 
Child extends Parent{
}
$obj = new Child();
$obj->getClass(); // Parent
?>
RQuadling at GMail dot com ¶
3 years ago
With regard to getting the class name from a namespaced class name, then using basename() seems to do the trick quite nicely.

<?php
namespace Foo\Bar;

abstract class 
Baz
{
  public function 
report()
  {
    echo
      
'__CLASS__        '__CLASS__' 'basename(__CLASS__), PHP_EOL,
      
'get_called_class 'get_called_class(), ' 'basename(get_called_class()), PHP_EOL;
  }
}

class 
Snafu extends Baz
{
}

(new 
Snafu)->report();
?>

produces output of ...

__CLASS__        Foo\Bar\Baz   Baz
get_called_class Foo\Bar\Snafu Snafu
XyQrTw ¶
1 year ago
To get class name without the Namespace you can use easily this trick :
<?php
namespace My\Long\Namespace;

class 
MyClass {

    static function 
getClassName() {
        return 
basename(__CLASS__);
       
// or with get_class();
        
return basename(get_class());
    }

}

echo \
My\Long\Namespace\MyClass::getClassName(); // Display : MyClass
?>
Anonymous ¶
3 years ago
If you want the path to an file if you have i file structure like this

project -> system -> libs -> controller.php
project -> system -> modules -> foo -> foo.php

and foo() in foo.php extends controller() in controller.php like this

<?PHP
namespace system\modules\foo;

class 
foo extends \system\libs\controller {
    public function 
__construct() {
        
parent::__construct();    
    }
}
?>

and you want to know the path to foo.php in controller() this may help you

<?PHP
namespace system\libs;

class 
controller {
    protected function 
__construct() {
        
$this->getChildPath();
    }
    protected function 
getChildPath() {
        echo 
dirname(get_class($this));
    }
}
?>

<?PHP
$f 
= new foo();  // system\modules\foo
?>
kiril (AT) aternus networks ¶
6 months ago
If you want the Class Name without the Namespace or if you've got here because basename() returns a dot (.) for the FQCN (Fully Qualified Class Name), here is the solution:

<?php
// FQCN: App\Http\Controllers\CustomerReportController

substr(self::class, (int)strrpos(self::class, '\\') + 1)

// returns: CustomerReportController
?>
Hayley Watson ¶
6 months ago
Although you can call a class's static methods from an instance of the class as though they were object instance methods, it's nice to know that, since classes are represented in PHP code by their names as strings, the same thing goes for the return value of get_class():

<?php
$t
->Faculty();
SomeClass::Faculty(); // $t instanceof SomeClass
"SomeClass"::Faculty();
get_class($t)::Faculty();
?>

The first is legitimate, but the last makes it clear to someone reading it that Faculty() is a static method (because the name of the method certainly doesn't).
dense ¶
1 year ago
well, if you call  get_class() on an aliased class, you will get the original class name

<?php

class Person {}

class_alias('Person''User');

$me = new User;

var_dumpget_class($me) ); // 'Person'

?>
Anonymous ¶
10 years ago
In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not 'know' the name of the calling subclass', so I use a backtrace to determine it. I don't like hacks like this, but as long as PHP doesn't have an alternative, this is what has to be done:

public function table_name() {
        $result = null;
        if (isset($this)) { // object context
            $result = get_class($this);
        }
        else { // class context
            $result = get_class();
            $trace = debug_backtrace();
            foreach ($trace as &$frame) {
                if (!isset($frame['class'])) {
                    break;
                }
                if ($frame['class'] != $result) {
                    if (!is_subclass_of($frame['class'], $result)) {
                        break;
                    }
                    $result = $frame['class'];
                }
            }
        }
        return $result;
    }
Aaron ¶
7 years ago
This can sometimes be used in place of get_called_class(). I used this function in a parent class to get the name of the class that extends it.
ozana at omdesign dot cz ¶
6 years ago
Simplest way how to gets Class without namespace 

<?php 
namespace a\b\c\d\e\f

class 
Foo 

  public function 
__toString() { 
    
$class explode('\\'__CLASS__); 
    return 
end($class); 
  } 


echo new 
Foo(); // prints Foo 
?>
Michael Richey ¶
6 years ago
Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it's not available.  Unlike other methods listed here, I chose not to prevent use of __construct() or __clone(). 

<?php 
abstract class Singleton 
    protected static 
$m_pInstance
    final public static function 
getInstance(){ 
        
$class = static::getClass(); 
        if(!isset(static::
$m_pInstance[$class])) { 
            static::
$m_pInstance[$class] = new $class
        } 
        return static::
$m_pInstance[$class]; 
    } 
    final public static function 
getClass(){ 
        return 
get_called_class(); 
    } 


// I don't remember where I found this, but this is to allow php < 5.3 to use this method. 
if (!function_exists('get_called_class')) { 
    function 
get_called_class($bt false$l 1) { 
        if (!
$bt
            
$bt debug_backtrace(); 
        if (!isset(
$bt[$l])) 
            throw new 
Exception("Cannot find called class -> stack level too deep."); 
        if (!isset(
$bt[$l]['type'])) { 
            throw new 
Exception('type not set'); 
        } 
        else 
            switch (
$bt[$l]['type']) { 
                case 
'::'
                    
$lines file($bt[$l]['file']); 
                    
$i 0
                    
$callerLine ''
                    do { 
                        
$i++; 
                        
$callerLine $lines[$bt[$l]['line'] - $i] . $callerLine
                    } while (
stripos($callerLine$bt[$l]['function']) === false); 
                    
preg_match('/([a-zA-Z0-9\_]+)::' $bt[$l]['function'] . '/'$callerLine$matches); 
                    if (!isset(
$matches[1])) { 
                        
// must be an edge case. 
                        
throw new Exception("Could not find caller class: originating method call is obscured."); 
                    } 
                    switch (
$matches[1]) { 
                        case 
'self'
                        case 
'parent'
                            return 
get_called_class($bt$l 1); 
                        default: 
                            return 
$matches[1]; 
                    } 
                
// won't get here. 
                
case '->': switch ($bt[$l]['function']) { 
                        case 
'__get'
                            
// edge case -> get class of calling object 
                            
if (!is_object($bt[$l]['object'])) 
                                throw new 
Exception("Edge case fail. __get called on non object."); 
                            return 
get_class($bt[$l]['object']); 
                        default: return 
$bt[$l]['class']; 
                    } 

                default: throw new 
Exception("Unknown backtrace method type"); 
            } 
    } 


class 
extends Singleton 


class 
extends Singleton 


$b B::getInstance(); 
echo 
'class: '.get_class($b); 

echo 
'<br />'

$c C::getInstance(); 
echo echo 
'class: '.get_class($c); 
?> 
This returns: 
class: b 
class: c
andregs at NOSPAM dot gmail dot NOSPAM dot com ¶
10 years ago
After reading the previous comments, this is the best I've done to get the final class name of a subclass:

<?php

class Singleton
{
   private static 
$_instances = array();
   protected final function 
__construct(){}
   
   
/**
    * @param string $classname
    * @return Singleton
    */
   
protected static function getInstance()
   {
      
$classname func_get_arg(0);
      if (! isset(
self::$_instances[$classname]))
      {
         
self::$_instances[$classname] = new $classname();
      }
      return 
self::$_instances[$classname];
   }
   
}

class 
Child extends Singleton
{
   
/**
    * @return Child
    */
   
public static function getInstance()
   {
      return 
parent::getInstance(get_class());
   }
}

?>

Subclasses must override "getInstance" and cannot override "__construct".
dodgie74 at NOSPAM dot yahoo dot NOSPAM dot co dot uk ¶
10 years ago
As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the "self" keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the "self" keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:

<?php
class Base
{
    protected 
$m_instanceName '';
    
    public static function 
classDisplayName()
    {
        return 
'Base Class';
    }
    
    public function 
instanceDisplayName()
    {
        
//here, we want "self" to refer to the actual class, which might be a derived class that inherits this method, not necessarily this base class
        
return $this->m_instanceName ' - ' self::classDisplayName();
    }
}

class 
Derived extends Base
{
    public function 
Derived$name )
    {
        
$this->m_instanceName $name;
    }
    
    public static function 
classDisplayName()
    {
        return 
'Derived Class';
    }
}

$o = new Derived('My Instance');
echo 
$o->instanceDisplayName();
?>

In the above example, assuming runtime binding (where the keyword "self" refers to the actual class on which the method was invoked rather than the class in which the method is defined) would produce the output:

My Instance - Derived Class

However, assuming compile-time binding (where the keyword "self" refers to the class in which the method is defined), which is how php works, the output would be:

My Instance - Base Class

The oddity here is that "$this" is bound at runtime to the actual class of the object (obviously) but "self" is bound at compile-time, which seems counter-intuitive to me. "self" is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which "self" ought to be useful.

However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to "self" being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the "self" keyword for static methods:

<?php
class Base
{
    protected 
$m_instanceName '';
    
    public static function 
classDisplayName()
    {
        return 
'Base Class';
    }
    
    public function 
instanceDisplayName()
    {
        
$realClass get_class($this);
        return 
$this->m_instanceName ' - ' call_user_func(array($realClass'classDisplayName'));
    }
}

class 
Derived extends Base
{
    public function 
Derived$name )
    {
        
$this->m_instanceName $name;
    }
    
    public static function 
classDisplayName()
    {
        return 
'Derived Class';
    }
}

$o = new Derived('My Instance');
echo 
$o->instanceDisplayName();
?>

Output:
My Instance - Derived Class

I realise that some people might respond "why don't use just just the class name with ' Class' appended instead of the classDisplayName() method", which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.

Apologies if this has been mentioned before.
bramus at bram dot us ¶
10 years ago
@ Frederik : 

<?
$class = $bt[count($bt) - 1]['class']; 
?>

should be

<?
$class = $bt[count($bt) - 2]['class'];
?>

;-)
yicheng zero-four at gmail dot com ¶
11 years ago
This a response to luke at liveoakinteractive dot com and davidc at php dot net.  Static methods and variables, by definition, are bound to class types not object instances.  You should not need to dynamically find out what class a static method belongs to, since the context of your code should make it quite obvious.  Your questions reveals that you probably don't quite understand OOP quite yet (it took me a while as well).

Luke, the observed behavior from your particular code snippet makes perfect sense when you think about it.  The method getclass() is defined in BooBoof, so the __CLASS__ macro would be bound to BooBoof and defined in relation to the BooBoof class.  The fact that CooCoof is a subclass of BooBoof just means that it gains a shortcut to BooBoof::getclass().  So, in effect, you are really asking (in a convoluted way): "What is the class to which belongs the method call BooBoof::getclass()?"  The correct solution (if you actually want/need to do this) is to simply implement CooCoof::getclass() { return __CLASS__; } inside of the CooCoof definition, and any childclasses that you want to mimic this behavior.  CooCoof::getclass() will have the expected behavior.
luke at liveoakinteractive dot com ¶
11 years ago
This note is a response to the earlier post by davidc at php dot net. Unfortunately, the solution posted for getting the class name from a static method does not work with inherited classes.

Observe the following:
<?php
class BooBoof {
  public static function 
getclass() {
    return 
__CLASS__;
  }

  public function 
retrieve_class() {
    return 
get_class($this);
  }
}

class 
CooCoof extends BooBoof {
}

echo 
CooCoof::getclass();
// outputs BooBoof

$coocoof = new CooCoof;
echo 
$coocoof->retrieve_class();
// outputs CooCoof
?>

__CLASS__ and get_class($this) do not work the same way with inherited classes. I have been thus far unable to determine a reliable way to get the actual class from a static method.
benjaminhill at gmail dot com ¶
11 years ago
More funkyness:

class Parent {
   function displayTableName() {
      echo get_class($this);
      echo get_class();
   }
}

class Child {
   function __construct() {
      $this->displayTableName();
   }
}

Will return 
- Child
- Parent

So when they say "the object isn't required in PHP5" - they don't really mean it.
Lanselot ¶
9 years ago
Beware if you're omitting the parameter on inherited classes.
It'll return the class name of the method where it's called.

<?php
class {
    function 
foo() {
      return 
get_class();
    }
}
class 
extends {
   function 
bar() {
      return 
get_class();
   }
}
$instance = new B();
echo 
$instance->bar(); //Prints 'B';
echo $instance->foo(); //Prints 'A';
?>
refrozen dot com ¶
12 years ago
philip at cornado dot com, it returns the value of the class from which it was called, rather than the instance's name... causing inheritance to result in unexpected returns
danbettles at yahoo dot co dot uk ¶
9 years ago
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using the new get_called_class function.  When called in a static method, this function returns the name of the class the call was made against.

<?php

abstract class Singleton {

    protected function 
__construct() {
    }

    final public static function 
getInstance() {
        static 
$aoInstance = array();

        
$calledClassName get_called_class();

        if (! isset (
$aoInstance[$calledClassName])) {
            
$aoInstance[$calledClassName] = new $calledClassName();
        }

        return 
$aoInstance[$calledClassName];
    }

    final private function 
__clone() {
    }
}

class 
DatabaseConnection extends Singleton {

    protected 
$connection;

    protected function 
__construct() {
        
// @todo Connect to the database
    
}

    public function 
__destruct() {
        
// @todo Drop the connection to the database
    
}
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn DatabaseConnection::getInstance();  // Returns single instance
?>

Full write-up in Oct 2008: http://danbettles.blogspot.com
Edward ¶
9 years ago
With Late Static Bindings, available as of PHP 5.3.0, it is now possible to implement an abstract Singleton class with minimal overhead in the child classes. Late static bindings are explained here: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

In short, it introduces a new 'static::' keyword, that is evaluated at runtime. In the following code I use it to determine the classname of the child Singleton class.

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;
    protected static $instance;
    
    protected function __construct() {
        static::$instance = $this;
        $this->init();
    }
    
    abstract protected function init();
    
    protected function getInstance() {
        $class = static::getClass();
        
        if (static::$instance===null) {
            static::$instance = new $class;
        }

        return static::$instance;
    }
    
    private static function getClass() {
        if (static::$__CLASS__ == __CLASS__) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }
        
        return static::$__CLASS__;
    }
}
?>

An example Singleton class can then be implemented as follows:

<?
class A extends Singleton {
    protected static $__CLASS__ = __CLASS__; // Provide this in each singleton class.

    protected function someFunction() {
        $instance = static::getInstance();
        // ...
    }
}
?>

Hope this helps you save some time :)
dave dot zap at gmail dot com ¶
9 years ago
Take care using the backtrace method to find the calling class of a static method, you should step backward through the array and find a match for your getInstance() function. In backtrace the class name you want is not always the last item in the array.

I will not post the whole singleton class here, but have made the following modification to Frederik Krautwald's method (found below)

<?php 
$bt 
debug_backtrace();
// this method is count($bt)-1) by Frederik will fall over when calling getInstance from within an include file.
//$class = $bt[count($bt) - 1]['class'];

for( $i=count($bt)-$i $i--)
{
    if(
$bt[$i]['function'] == 'getInstance')
    {
        
$class $bt[$i]['class'];
        break;
    }
}
?>
MagicalTux at FF.ST ¶
14 years ago
Note that the constant __CLASS__ is different from get_class($this) :
<?
  class test {
    function whoami() {
      echo "Hello, I'm whoami 1 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
    }
  }
  class test2 extends test {
    function whoami2() {
      echo "Hello, I'm whoami 2 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
      parent::whoami(); // call parent whoami() function
    }
  }
  $test=new test;
  $test->whoami();
  $test2=new test2;
  $test2->whoami();
  $test2->whoami2();
?>

The output is :
Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

Hello, I'm whoami 2 !
Value of __CLASS__ : test2
Value of get_class() : test2

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

In fact, __CLASS__ returns the name of the class the function is in and get_class($this) returns the name of the class which was created.


728x90

Are you worried about your Apache server performance? Okay let’s talk about Apache Multi-Processing Modules (MPMs). There is a documentation for Apache MPM but who has got time to read the documentations. Let’s talk in simple plain english about Apache Multi-Processing Modules (MPMs). All you need is 15 mins to learn Apache MPMs(happy-face).

What

The MPMs are used to change the basic functionality of the web server. It’s possible due to Apache’s modular design. The MPM, or Multi Processing Module, you use is responsible for just about the entire HTTP session. Starting from listening on the network, taking requests in and most importantly, how to handle those requests. With the MPM you use Apache’s behaviour will change. Apache offers three MPMs to choose from; PreforkWorker, and Event. You might be wondering which MPM module you should choose. Answer is right below.

How do I select which Apache MPM to use?

Above links explains about the three MPM modules and when to use them. If you don’t know about the Apache MPMs or which one to use , time to start reading.

How

1. Check what your Apache server has got

Most of the Apache server comes with Prefork module. To make sure whether your server has got Prefork, type the below command and see.

See the output below

If the Prefork Module is installed it should be shown under compiled in modules. prefork.c is shown on the list.

2. Let’s install Apache Worker MPM

Let’s configure Worker MPM. So time to install Worker.

If you are willing to install Prefork or Event MPMs it should be as below

When the installation is completed type apache2ctl -l and see whether the prefork.c/worker.c shows up under “Compiled in modules”.

Note in Ubuntu you can only have one MPM module at a time. It means if you install Worker while the server has got Prefork, Prefork will be automatically removed. When you are switching MPMs it’s a good idea to backup your .conf files.

3. Let’s understand Apache MPM directives

Please read the comments below to understand about the each directives and what they do. Below configurations are extracted from apache2.conf

If you need more information on directives check the documentation.

4. Time to customise the Apache Worker directives as we need

 

Before customising the directives you need to understand how the directives work. Let me explain in plain English. Server will start 2 child processes which is determined by StartServersdirective. Each process will start 20 threads which is determined by ThreadsPerChild directive so this means 2 process can service only 40 concurrent connections/clients(i.e. 20×2=40). So what if more requests come in.

Now if more concurrent users come, then another child process will start, that can serve another 20 users. But how many child processes can be started is controlled by ServerLimit parameter, this means that in the configuration above, I can have 10 child processes in total, with each child process can handle 20 thread, in total handling 10×20=200 concurrent users.

But there is a problem, number defined in MaxClients is 100 here, this means that after 5 child processes, no extra process will start since we have defined an upper cap of MaxClients. This also means that if I set MaxClients to 500, after 10 child processes and 200 connections, no extra process will start and we cannot service more than 200 concurrent clients even if we have increase the MaxClient parameter. In this case, we need to also increase ServerLimit to 500/20 i.e. MaxClients/ThreadsPerChild=25

Okay now you know the directives and how they work, the problem is how to calculate the directives. Let’s jump into calculating directive values.

You can use this shell script to determine an average amount of memory consumed by one Apache process. In addition to that it’ll show total amount of memory consumed by all Apache processes. Just unzip and execute with sh command. Accurate results will be shown when server is under heavy load.

The output

if in average, let’s assume that one Apache process consumes 50MB RAM and server has got RAM is 2048MB, and you want to leave 512MB for the rest of the processes, then:

So that’s how you configure Apache Multi-Processing Modules. If you have any questions let me know in the comments below. Your feedback is highly appreciated(happy-face).

Image Courtesy : http://www.vps.net/

728x90

Table of Contents

Introduction

Apache is a powerful and capable open-source web server, designed to provide a balance of flexibility, portability, and performance. Apache optimization is an important task for every system administrator.

You can improve Apache's performance by customizing the Apache configuration without needing to add additional hardware like RAM, CPU etc.

This post describes various Apache configuration options that can be used to improve Apache performance without adding additional hardware resources to your system.

Requirements

  • A server running CentOS v.7
  • Apache installed and running

MaxKeepAliveRequests

MaxKeepAliveRequests is the maximum number of requests to serve on a TCP connection. It limits the number of requests allowed per connection. If it is set to 0, unlimited requests will be allowed. You can set it to any value you desire.

Keep this setting to a high value for maximum server performance. The recommended value of MaxKeepAliveRequests is 500.

To change this setting, edit the Apache configuration file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

MaxKeepAliveRequests 500

Save and close the file when you are finished.

KeepAliveTimeout

KeepAliveTimeout defines the number of seconds Apache will wait for the new request from connected clients before closing the connection. (Once the server receives a request, the Timeout directive applies instead.)

By default Keepalive is disabled in CentOS 7. If Keepalive is set to on, it is a good idea to set the KeepAliveTimeout value low.

The recommended KeepAliveTimeout can be between 1 to 5.

You can do this by editing Apache configuration file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

KeepAliveTimeout 5

Save and close the file when you are finished.

KeepAlive

KeepAlive sets whether the server allows more than one request per connection. It can be used to prevent any one client from consuming too much of the server's resources.

By default KeepAlive is disabled in CentOS 7. Once the Apache server is getting requests from hundreds and thousands of IPs at once, this setting should be On.

You can enable this setting by editing Apache configuration file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

KeepAlive On

Save and close the file when you are finished.

Configure MPM Prefork

One reason for poor Apache performance is that Apache is having trouble coping with the load. The Apache MPM (Multi-Processing Module) can help.

mpm_prefork_module is included and enabled in the default Apache installation on CentOS 7. To confirm this run the following command:

sudo apachectl -t -D DUMP_MODULES |grep mpm

You should see mpm_prefork_module (shared) if mod_deflate is installed and enabled.

You can make Apache performance better using the Apache MPM prefork module. To do this, set the following parameters in your Apache configuration file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following lines:

KeepAlive Off
<IfModule prefork.c>
   StartServers        5
   MinSpareServers     5
   MaxSpareServers     10
   MaxClients          150
   MaxRequestsPerChild 3000
</IfModule>

Save and close the file, then restart Apache to reflect these changes.

sudo apachectl restart

Explanations

StartServers: This directive sets the number of child server processes created on startup. It is a good idea to increase this number on a high-load server, so the server is ready to handle a lot of connections.

MinSpareServers: This directive sets the minimum number of idle child server processes. This value will need to be tuned for high-load servers.

MaxSpareServers: This directive sets the maximum number of idle child server processes. When there are more idle child server processes than defined by MaxSpareServers the idle process will be killed.

MaxClients: This directive sets the maximum number of simultaneous requests that Apache will handle. When this limit has been reached, any other connection attempts will be queued.

Number of MaxClients = (Total RAM memory – RAM memory used for other process except Apache process) / (Memory used by a single Apache process)

MaxRequestsPerChild: This directive sets how many requests a child process will handle before terminating. Once the limit has been reached, the child process will die.

Note: If this value is 0, then the process will never die.

AllowOverride

If AllowOverride is set to 'All', then Apache will attempt to open a .htaccess file in each directory that it visits.

For example:

 DocumentRoot /vaw/www/html/website1
 <Directory /> 
 AllowOverride All
 </Directory>

If a request is made for URI /index.html, then Apache will attempt to open .htaccess file in //var//var/www//var/www/html/ and /var/www/html/website1/.

Therefore, it is good idea to add AllowOverride all for a specific directory only:

 DocumentRoot /vaw/www/html/example
 <Directory /var/wwww/html/example/admin> 
   AllowOverride All
 </Directory>

DNS Lookups

The biggest reason for Apache web server slowdowns is the time required to perform DNS lookups. Apache will record the full host name of each incoming client connection in its access.log file. Resolving each one eats up a significant chunk of time.

The HostnameLookups option enables DNS lookup so that hostnames can be logged instead of the IP address. By default HostnameLookups is Off in Apache.

You can verify that this is the case by editing the Apache config file:

sudo nano /etc/httpd/conf/httpd.conf

Be sure the HostnameLookups line reads:

HostnameLookups Off

Save and close the file when you are finished, then restart Apache to reflect changes.

sudo apachectl restart

Conclusion

Configuring Apache for maximum performance is very easy. You can experiment with various available options and measure the web server performance with tools like ab and httperf. Feel free to leave me a comment if you have any questions.

728x90

Description:A collection of directives that are implemented by more than one multi-processing module (MPM)
Status:MPM
top

CoreDumpDirectory Directive

Description:Directory where Apache HTTP Server attempts to switch before dumping core
Syntax:CoreDumpDirectory directory
Default:See usage for the default setting
Context:server config
Status:MPM
Module:event, worker, prefork

This controls the directory to which Apache httpd attempts to switch before dumping core. If your operating system is configured to create core files in the working directory of the crashing process,CoreDumpDirectory is necessary to change working directory from the default ServerRoot directory, which should not be writable by the user the server runs as.

If you want a core dump for debugging, you can use this directive to place it in a different location. This directive has no effect if your operating system is not configured to write core files to the working directory of the crashing processes.

Core Dumps on Linux

If Apache httpd starts as root and switches to another user, the Linux kernel disables core dumps even if the directory is writable for the process. Apache httpd (2.0.46 and later) reenables core dumps on Linux 2.4 and beyond, but only if you explicitly configure a CoreDumpDirectory.

Core Dumps on BSD

To enable core-dumping of suid-executables on BSD-systems (such as FreeBSD), set kern.sugid_coredump to 1.

Specific signals

CoreDumpDirectory processing only occurs for a select set of fatal signals: SIGFPE, SIGILL, SIGABORT, SIGSEGV, and SIGBUS.

On some operating systems, SIGQUIT also results in a core dump but does not go through CoreDumpDirectory or EnableExceptionHook processing, so the core location is dictated entirely by the operating system.

top

EnableExceptionHook Directive

Description:Enables a hook that runs exception handlers after a crash
Syntax:EnableExceptionHook On|Off
Default:EnableExceptionHook Off
Context:server config
Status:MPM
Module:event, worker, prefork

For safety reasons this directive is only available if the server was configured with the --enable-exception-hook option. It enables a hook that allows external modules to plug in and do something after a child crashed.

There are already two modules, mod_whatkilledus and mod_backtrace that make use of this hook. Please have a look at Jeff Trawick's EnableExceptionHook site for more information about these.

top

GracefulShutdownTimeout Directive

Description:Specify a timeout after which a gracefully shutdown server will exit.
Syntax:GracefulShutdownTimeout seconds
Default:GracefulShutdownTimeout 0
Context:server config
Status:MPM
Module:event, worker, prefork
Compatibility:Available in version 2.2 and later

The GracefulShutdownTimeout specifies how many seconds after receiving a "graceful-stop" signal, a server should continue to run, handling the existing connections.

Setting this value to zero means that the server will wait indefinitely until all remaining requests have been fully served.

top

Listen Directive

Description:IP addresses and ports that the server listens to
Syntax:Listen [IP-address:]portnumber [protocol]
Context:server config
Status:MPM
Module:event, worker, prefork, mpm_winnt, mpm_netware, mpmt_os2
Compatibility:The protocol argument was added in 2.1.5

The Listen directive instructs Apache httpd to listen to only specific IP addresses or ports; by default it responds to requests on all IP interfaces. Listen is now a required directive. If it is not in the config file, the server will fail to start. This is a change from previous versions of Apache httpd.

The Listen directive tells the server to accept incoming requests on the specified port or address-and-port combination. If only a port number is specified, the server listens to the given port on all interfaces. If an IP address is given as well as a port, the server will listen on the given port and interface.

Multiple Listen directives may be used to specify a number of addresses and ports to listen to. The server will respond to requests from any of the listed addresses and ports.

For example, to make the server accept connections on both port 80 and port 8000, use:

Listen 80
Listen 8000

To make the server accept connections on two specified interfaces and port numbers, use

Listen 192.170.2.1:80
Listen 192.170.2.5:8000

IPv6 addresses must be surrounded in square brackets, as in the following example:

Listen [2001:db8::a00:20ff:fea7:ccea]:80

The optional protocol argument is not required for most configurations. If not specified, https is the default for port 443 and http the default for all other ports. The protocol is used to determine which module should handle a request, and to apply protocol specific optimizations with the AcceptFilter directive.

You only need to set the protocol if you are running on non-standard ports. For example, running an https site on port 8443:

Listen 192.170.2.1:8443 https

Error condition

Multiple Listen directives for the same ip address and port will result in an Address already in use error message.

See also

top

ListenBackLog Directive

Description:Maximum length of the queue of pending connections
Syntax:ListenBacklog backlog
Default:ListenBacklog 511
Context:server config
Status:MPM
Module:event, worker, prefork, mpm_winnt, mpm_netware, mpmt_os2

The maximum length of the queue of pending connections. Generally no tuning is needed or desired, however on some systems it is desirable to increase this when under a TCP SYN flood attack. See the backlog parameter to the listen(2) system call.

This will often be limited to a smaller number by the operating system. This varies from OS to OS. Also note that many OSes do not use exactly what is specified as the backlog, but use a number based on (but normally larger than) what is set.

top

ListenCoresBucketsRatio Directive

Description:Ratio between the number of CPU cores (online) and the number of listeners' buckets
Syntax:ListenCoresBucketsRatio ratio
Default:ListenCoresBucketsRatio 0 (disabled)
Context:server config
Status:MPM
Module:event, worker, prefork
Compatibility:Available in Apache HTTP Server 2.4.17, with a kernel supporting the socket option SO_REUSEPORT and distributing new connections evenly across listening processes' (or threads') sockets using it (eg. Linux 3.9 and later, but not the current implementations of SO_REUSEPORT in *BSDs.

A ratio between the number of (online) CPU cores and the number of listeners' buckets can be used to make Apache HTTP Server create num_cpu_cores / ratio listening buckets, each containing its own Listen-ing socket(s) on the same port(s), and then make each child handle a single bucket (with round-robin distribution of the buckets at children creation time).

Meaning of "online" CPU core

On Linux (and also BSD) a CPU core can be turned on/off if Hotplug is configured, therefore ListenCoresBucketsRatio needs to take this parameter into account while calculating the number of buckets to create.

ListenCoresBucketsRatio can improve the scalability when accepting new connections is/becomes the bottleneck. On systems with a large number of CPU cores, enabling this feature has been tested to show significant performances improvement and shorter responses time.

There must be at least twice the number of CPU cores than the configured ratio for this to be active. The recommended ratio is 8, hence at least 16 cores should be available at runtime when this value is used. The right ratio to obtain maximum performance needs to be calculated for each target system, testing multiple values and observing the variations in your key performance metrics.

This directive influences the calculation of the MinSpareThreads and MaxSpareThreads lower bound values. The number of children processes needs to be a multiple of the number of buckets to optimally accept connections.

Multiple Listeners or Apache HTTP servers on the same IP address and port

Setting the SO_REUSEPORT option on the listening socket(s) consequently allows multiple processes (sharing the same EUID, e.g. root) to bind to the the same IP address and port, without the binding error raised by the system in the usual case.

This also means that multiple instances of Apache httpd configured on a same IP:port and with a positive ListenCoresBucketsRatio would start without an error too, and then run with incoming connections evenly distributed accross both instances (this is NOT a recommendation or a sensible usage in any case, but just a notice that it would prevent such possible issues to be detected).

Within the same instance, Apache httpd will check and fail to start if multiple Listen directives on the exact same IP (or hostname) and port are configured, thus avoiding the creation of some duplicated buckets which would be useless and kill performances. However it can't (and won't try harder to) catch all the possible overlapping cases (like a hostname resolving to an IP used elsewhere).

top

MaxConnectionsPerChild Directive

Description:Limit on the number of connections that an individual child server will handle during its life
Syntax:MaxConnectionsPerChild number
Default:MaxConnectionsPerChild 0
Context:server config
Status:MPM
Module:event, worker, prefork, mpm_winnt, mpm_netware, mpmt_os2
Compatibility:Available Apache HTTP Server 2.3.9 and later. The old name MaxRequestsPerChild is still supported.

The MaxConnectionsPerChild directive sets the limit on the number of connections that an individual child server process will handle. After MaxConnectionsPerChild connections, the child process will die. If MaxConnectionsPerChild is 0, then the process will never expire.

Setting MaxConnectionsPerChild to a non-zero value limits the amount of memory that process can consume by (accidental) memory leakage.

top

MaxMemFree Directive

Description:Maximum amount of memory that the main allocator is allowed to hold without calling free()
Syntax:MaxMemFree KBytes
Default:MaxMemFree 2048
Context:server config
Status:MPM
Module:event, worker, prefork, mpm_winnt, mpm_netware

The MaxMemFree directive sets the maximum number of free Kbytes that every allocator is allowed to hold without calling free(). In threaded MPMs, every thread has its own allocator. When set to zero, the threshold will be set to unlimited.

top

MaxRequestWorkers Directive

Description:Maximum number of connections that will be processed simultaneously
Syntax:MaxRequestWorkers number
Default:See usage for details
Context:server config
Status:MPM
Module:event, worker, prefork

The MaxRequestWorkers directive sets the limit on the number of simultaneous requests that will be served. Any connection attempts over the MaxRequestWorkers limit will normally be queued, up to a number based on the ListenBacklog directive. Once a child process is freed at the end of a different request, the connection will then be serviced.

For non-threaded servers (i.e., prefork), MaxRequestWorkers translates into the maximum number of child processes that will be launched to serve requests. The default value is 256; to increase it, you must also raise ServerLimit.

For threaded and hybrid servers (e.g. event or worker) MaxRequestWorkers restricts the total number of threads that will be available to serve clients. For hybrid MPMs the default value is 16(ServerLimit) multiplied by the value of 25 (ThreadsPerChild). Therefore, to increase MaxRequestWorkers to a value that requires more than 16 processes, you must also raise ServerLimit.

MaxRequestWorkers was called MaxClients before version 2.3.13. The old name is still supported.

top

MaxSpareThreads Directive

Description:Maximum number of idle threads
Syntax:MaxSpareThreads number
Default:See usage for details
Context:server config
Status:MPM
Module:event, worker, mpm_netware, mpmt_os2

Maximum number of idle threads. Different MPMs deal with this directive differently.

For worker and event, the default is MaxSpareThreads 250. These MPMs deal with idle threads on a server-wide basis. If there are too many idle threads in the server then child processes are killed until the number of idle threads is less than this number. Additional processes/threads might be created if ListenCoresBucketsRatio is enabled.

For mpm_netware the default is MaxSpareThreads 100. Since this MPM runs a single-process, the spare thread count is also server-wide.

mpmt_os2 works similar to mpm_netware. For mpmt_os2 the default value is 10.

Restrictions

The range of the MaxSpareThreads value is restricted. Apache httpd will correct the given value automatically according to the following rules:

See also

top

MinSpareThreads Directive

Description:Minimum number of idle threads available to handle request spikes
Syntax:MinSpareThreads number
Default:See usage for details
Context:server config
Status:MPM
Module:event, worker, mpm_netware, mpmt_os2

Minimum number of idle threads to handle request spikes. Different MPMs deal with this directive differently.

worker and event use a default of MinSpareThreads 75 and deal with idle threads on a server-wide basis. If there aren't enough idle threads in the server then child processes are created until the number of idle threads is greater than number. Additional processes/threads might be created if ListenCoresBucketsRatio is enabled.

mpm_netware uses a default of MinSpareThreads 10 and, since it is a single-process MPM, tracks this on a server-wide bases.

mpmt_os2 works similar to mpm_netware. For mpmt_os2 the default value is 5.

See also

top

PidFile Directive

Description:File where the server records the process ID of the daemon
Syntax:PidFile filename
Default:PidFile logs/httpd.pid
Context:server config
Status:MPM
Module:event, worker, prefork, mpm_winnt, mpmt_os2

The PidFile directive sets the file to which the server records the process id of the daemon. If the filename is not absolute then it is assumed to be relative to the ServerRoot.

Example

PidFile /var/run/apache.pid

It is often useful to be able to send the server a signal, so that it closes and then re-opens its ErrorLog and TransferLog, and re-reads its configuration files. This is done by sending a SIGHUP (kill -1) signal to the process id listed in the PidFile.

The PidFile is subject to the same warnings about log file placement and security.

Note

As of Apache HTTP Server 2, we recommended that you only use the apachectl script, or the init script that your OS provides, for (re-)starting or stopping the server.

top

ReceiveBufferSize Directive

Description:TCP receive buffer size
Syntax:ReceiveBufferSize bytes
Default:ReceiveBufferSize 0
Context:server config
Status:MPM
Module:event, worker, prefork, mpm_winnt, mpm_netware, mpmt_os2

The server will set the TCP receive buffer size to the number of bytes specified.

If set to the value of 0, the server will use the OS default.

top

ScoreBoardFile Directive

Description:Location of the file used to store coordination data for the child processes
Syntax:ScoreBoardFile file-path
Default:ScoreBoardFile logs/apache_runtime_status
Context:server config
Status:MPM
Module:event, worker, prefork, mpm_winnt

Apache HTTP Server uses a scoreboard to communicate between its parent and child processes. Some architectures require a file to facilitate this communication. If the file is left unspecified, Apache httpd first attempts to create the scoreboard entirely in memory (using anonymous shared memory) and, failing that, will attempt to create the file on disk (using file-based shared memory). Specifying this directive causes Apache httpd to always create the file on the disk.

Example

ScoreBoardFile /var/run/apache_runtime_status

File-based shared memory is useful for third-party applications that require direct access to the scoreboard.

If you use a ScoreBoardFile then you may see improved speed by placing it on a RAM disk. But be careful that you heed the same warnings about log file placement and security.

See also

top

SendBufferSize Directive

Description:TCP buffer size
Syntax:SendBufferSize bytes
Default:SendBufferSize 0
Context:server config
Status:MPM
Module:event, worker, prefork, mpm_winnt, mpm_netware, mpmt_os2

Sets the server's TCP send buffer size to the number of bytes specified. It is often useful to set this past the OS's standard default value on high speed, high latency connections (i.e., 100ms or so, such as transcontinental fast pipes).

If set to the value of 0, the server will use the default value provided by your OS.

Further configuration of your operating system may be required to elicit better performance on high speed, high latency connections.

On some operating systems, changes in TCP behavior resulting from a larger SendBufferSize may not be seen unless EnableSendfile is set to OFF. This interaction applies only to static files.

top

ServerLimit Directive

Description:Upper limit on configurable number of processes
Syntax:ServerLimit number
Default:See usage for details
Context:server config
Status:MPM
Module:event, worker, prefork

For the prefork MPM, this directive sets the maximum configured value for MaxRequestWorkers for the lifetime of the Apache httpd process. For the worker and event MPMs, this directive in combination with ThreadLimit sets the maximum configured value for MaxRequestWorkers for the lifetime of the Apache httpd process. For the event MPM, this directive also defines how many old server processes may keep running and finish processing open connections. Any attempts to change this directive during a restart will be ignored, but MaxRequestWorkers can be modified during a restart.

Special care must be taken when using this directive. If ServerLimit is set to a value much higher than necessary, extra, unused shared memory will be allocated. If both ServerLimit and MaxRequestWorkers are set to values higher than the system can handle, Apache httpd may not start or the system may become unstable.

With the prefork MPM, use this directive only if you need to set MaxRequestWorkers higher than 256 (default). Do not set the value of this directive any higher than what you might want to set MaxRequestWorkers to.

With worker, use this directive only if your MaxRequestWorkers and ThreadsPerChild settings require more than 16 server processes (default). Do not set the value of this directive any higher than the number of server processes required by what you may want for MaxRequestWorkers and ThreadsPerChild.

With event, increase this directive if the process number defined by your MaxRequestWorkers and ThreadsPerChild settings, plus the number of gracefully shutting down processes, is more than 16 server processes (default).

Note

There is a hard limit of ServerLimit 20000 compiled into the server (for the prefork MPM 200000). This is intended to avoid nasty effects caused by typos. To increase it even further past this limit, you will need to modify the value of MAX_SERVER_LIMIT in the mpm source file and rebuild the server.

See also

top

StartServers Directive

Description:Number of child server processes created at startup
Syntax:StartServers number
Default:See usage for details
Context:server config
Status:MPM
Module:event, worker, prefork, mpmt_os2

The StartServers directive sets the number of child server processes created on startup. As the number of processes is dynamically controlled depending on the load, (see MinSpareThreads,MaxSpareThreads, MinSpareServers, MaxSpareServers) there is usually little reason to adjust this parameter.

The default value differs from MPM to MPM. worker and event default to StartServers 3; prefork defaults to 5; mpmt_os2 defaults to 2.

top

StartThreads Directive

Description:Number of threads created on startup
Syntax:StartThreads number
Default:See usage for details
Context:server config
Status:MPM
Module:mpm_netware

Number of threads created on startup. As the number of threads is dynamically controlled depending on the load, (see MinSpareThreads, MaxSpareThreads, MinSpareServers, MaxSpareServers) there is usually little reason to adjust this parameter.

For mpm_netware the default is StartThreads 50 and, since there is only a single process, this is the total number of threads created at startup to serve requests.

top

ThreadLimit Directive

Description:Sets the upper limit on the configurable number of threads per child process
Syntax:ThreadLimit number
Default:See usage for details
Context:server config
Status:MPM
Module:event, worker, mpm_winnt

This directive sets the maximum configured value for ThreadsPerChild for the lifetime of the Apache httpd process. Any attempts to change this directive during a restart will be ignored, but ThreadsPerChild can be modified during a restart up to the value of this directive.

Special care must be taken when using this directive. If ThreadLimit is set to a value much higher than ThreadsPerChild, extra unused shared memory will be allocated. If both ThreadLimitand ThreadsPerChild are set to values higher than the system can handle, Apache httpd may not start or the system may become unstable. Do not set the value of this directive any higher than your greatest predicted setting of ThreadsPerChild for the current run of Apache httpd.

The default value for ThreadLimit is 1920 when used with mpm_winnt and 64 when used with the others.

Note

There is a hard limit of ThreadLimit 20000 (or ThreadLimit 100000 with event, ThreadLimit 15000 with mpm_winnt) compiled into the server. This is intended to avoid nasty effects caused by typos. To increase it even further past this limit, you will need to modify the value of MAX_THREAD_LIMIT in the mpm source file and rebuild the server.

top

ThreadsPerChild Directive

Description:Number of threads created by each child process
Syntax:ThreadsPerChild number
Default:See usage for details
Context:server config
Status:MPM
Module:event, worker, mpm_winnt

This directive sets the number of threads created by each child process. The child creates these threads at startup and never creates more. If using an MPM like mpm_winnt, where there is only one child process, this number should be high enough to handle the entire load of the server. If using an MPM like worker, where there are multiple child processes, the total number of threads should be high enough to handle the common load on the server.

The default value for ThreadsPerChild is 64 when used with mpm_winnt and 25 when used with the others.

top

ThreadStackSize Directive

Description:The size in bytes of the stack used by threads handling client connections
Syntax:ThreadStackSize size
Default:65536 on NetWare; varies on other operating systems
Context:server config
Status:MPM
Module:event, worker, mpm_winnt, mpm_netware, mpmt_os2
Compatibility:Available in Apache HTTP Server 2.1 and later

The ThreadStackSize directive sets the size of the stack (for autodata) of threads which handle client connections and call modules to help process those connections. In most cases the operating system default for stack size is reasonable, but there are some conditions where it may need to be adjusted:

  • On platforms with a relatively small default thread stack size (e.g., HP-UX), Apache httpd may crash when using some third-party modules which use a relatively large amount of autodata storage. Those same modules may have worked fine on other platforms where the default thread stack size is larger. This type of crash is resolved by setting ThreadStackSize to a value higher than the operating system default. This type of adjustment is necessary only if the provider of the third-party module specifies that it is required, or if diagnosis of an Apache httpd crash indicates that the thread stack size was too small.
  • On platforms where the default thread stack size is significantly larger than necessary for the web server configuration, a higher number of threads per child process will be achievable if ThreadStackSize is set to a value lower than the operating system default. This type of adjustment should only be made in a test environment which allows the full set of web server processing can be exercised, as there may be infrequent requests which require more stack to process. The minimum required stack size strongly depends on the modules used, but any change in the web server configuration can invalidate the current ThreadStackSize setting.
  • On Linux, this directive can only be used to increase the default stack size, as the underlying system call uses the value as a minimum stack size. The (often large) soft limit for ulimit -s(8MB if unlimited) is used as the default stack size.
It is recommended to not reduce ThreadStackSize unless a high number of threads per child process is needed. On some platforms (including Linux), a setting of 128000 is already too low and causes crashes with some common modules.


+ Recent posts