社区
Android
帖子详情
用百度地图API时,The following classes could not be instantiated
onrush
2013-02-17 11:00:48
用百度地图API时,The following classes could not be instantiated:
- com.baidu.mapapi.map.MapView (Open Class, Show Error Log)怎么回事
以前试建了几个project都可以。现在突然不可以了
...全文
893
5
打赏
收藏
用百度地图API时,The following classes could not be instantiated
用百度地图API时,The following classes could not be instantiated: - com.baidu.mapapi.map.MapView (Open Class, Show Error Log)怎么回事 以前试建了几个project都可以。现在突然不可以了
复制链接
扫一扫
分享
转发到动态
举报
写回复
配置赞助广告
用AI写文章
5 条
回复
切换为时间正序
请发表友善的回复…
发表回复
打赏红包
万物为铜
2015-08-12
打赏
举报
回复
大神求告知。
qi19900808
2013-07-05
打赏
举报
回复
没有一个号的方法么?求解释
bcf102
2013-07-04
打赏
举报
回复
纯属猜测,你手机上有没有其它的使用百度map sdk的测试应用或者之类的东西?删掉后再运行你自己的试一下
追念
2013-07-03
打赏
举报
回复
请问谁解决了这个问题?
Jhon_Easter
2013-06-24
打赏
举报
回复
LZ解决没啊· 我也遇到这么问题
Google C++ Style Guide(Google C++编程规范)高清PDF
Table of Contents Header Fil
es
The #define Guard Header File Dependenci
es
Inline Functions The -inl.h Fil
es
Function Parameter Ordering Nam
es
and Order of Includ
es
Scoping Nam
es
pac
es
N
es
ted
Class
es
Nonmember, Static Member, and Global Functions Local Variabl
es
Static and Global Variabl
es
Class
es
Doing Work in Constructors Default Constructors Explicit Constructors Copy Constructors Structs vs.
Class
es
Inheritance Multiple Inheritance Interfac
es
Operator Overloading Acc
es
s Control Declaration Order Write Short Functions Google-Specific Magic Smart Pointers cpplint Other C++ Featur
es
Reference Arguments Function Overloading Default Arguments Variable-Length Arrays and alloca() Friends Exceptions Run-Time Type Information (RTTI) Casting Streams Preincrement and Predecrement Use of const Integer Typ
es
64-bit Portability Preproc
es
sor Macros 0 and NULL sizeof Boost C++0x Naming General Naming Rul
es
File Nam
es
Type Nam
es
Variable Nam
es
Const
ant
Nam
es
Function Nam
es
Nam
es
pace Nam
es
Enumerator Nam
es
Macro Nam
es
Exceptions to Naming Rul
es
Comments Comment Style File Comments
Class
Comments Function Comments Variable Comments Implementation Comments Punctuation, Spelling and Grammar TODO Comments Deprecation Comments Formatting Line Length Non-ASCII Characters Spac
es
vs. Tabs Function Declarations and Definitions Function Calls Conditionals Loops and Switch Statements Pointer and Reference Expr
es
sions Boolean Expr
es
sions Return Valu
es
Variable and Array Initialization Preproc
es
sor Directiv
es
Class
Format Constructor Initializer Lists Nam
es
pace Formatting Horizontal Whit
es
pace Vertical Whit
es
pace Exceptions to the Rul
es
Existing Non-conform
ant
Code Windows Code Import
ant
Note Displaying Hidden Details in this Guide link ▶This style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see "Hooray" appear below. Hooray! Now you know you can expand points to get more details. Alternatively, there's an "expand all" at the top of this document. Background C++ is the main development language used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful featur
es
, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain. The goal of this guide is to manage this complexity by d
es
cribing in detail the dos and don'ts of writing C++ code. Th
es
e rul
es
exist to keep the code base manageable while still allowing coders to use C++ language featur
es
productively. Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since th
es
e conventions cover far more than just source file formatting. One way in which we keep the code base manageable is by enforcing consistency. It is very import
ant
that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and
following
conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invari
ant
s are true about them. Creating common, required idioms and patterns mak
es
code much easier to understand. In some cas
es
there might be good arguments for changing certain style rul
es
, but we nonethel
es
s keep things as they are in order to pr
es
erve consistency. Another issue this guide addr
es
s
es
is that of C++ feature bloat. C++ is a huge language with many advanced featur
es
. In some cas
es
we constrain, or even ban, use of certain featur
es
. We do this to keep code simple and to avoid the various common errors and problems that th
es
e featur
es
can cause. This guide lists th
es
e featur
es
and explains why their use is r
es
tricted. Open-source projects developed by Google conform to the requirements in this guide. Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language. Header Fil
es
In general, every .cc file should have an assoc
iated
.h file. There are some common exceptions, such as unitt
es
ts and small .cc fil
es
containing just a main() function. Correct use of header fil
es
can make a huge difference to the readability, size and performance of your code. The
following
rul
es
will guide you through the various pitfalls of using header fil
es
. The #define Guard link ▶All header fil
es
should have #define guards to prevent multiple inclusion. The format of the symbol name should be ___H_. To guar
ant
ee uniquen
es
s, they should be based on the full path in a project's source tree. For example, the file foo/src/bar/baz.h in project foo should have the
following
guard: #ifndef FOO_BAR_BAZ_H_ #define FOO_BAR_BAZ_H_ ... #endif // FOO_BAR_BAZ_H_ Header File Dependenci
es
link ▶Don't use an #include when a forward declaration would suffice. When you include a header file you introduce a dependency that will cause your code to be recompiled whenever the header file chang
es
. If your header file includ
es
other header fil
es
, any change to those fil
es
will cause any code that includ
es
your header to be recompiled. Therefore, we prefer to minimize includ
es
, particularly includ
es
of header fil
es
in other header fil
es
. You can signific
ant
ly minimize the number of header fil
es
you need to include in your own header fil
es
by using forward declarations. For example, if your header file us
es
the File
class
in ways that do not require acc
es
s to the declaration of the File
class
, your header file can just forward declare
class
File;
inst
ead of having to #include "file/base/file.h". How can we use a
class
Foo in a header file without acc
es
s to its definition? We can declare data members of type Foo* or Foo&. We can declare (but not define) functions with arguments, and/or return valu
es
, of type Foo. (One exception is if an argument Foo or const Foo& has a non-explicit, one-argument constructor, in which case we need the full definition to support automatic type conversion.) We can declare static data members of type Foo. This is because static data members are defined outside the
class
definition. On the other hand, you must include the header file for Foo if your
class
sub
class
es
Foo or has a data member of type Foo. Sometim
es
it mak
es
sense to have pointer (or better, scoped_ptr) members
inst
ead of object members. However, this complicat
es
code readability and impos
es
a performance penalty, so avoid doing this transformation if the only purpose is to minimize includ
es
in header fil
es
. Of course, .cc fil
es
typically do require the definitions of the
class
es
they use, and usually have to include several header fil
es
. Note: If you use a symbol Foo in your source file, you should bring in a definition for Foo yourself, either via an #include or via a forward declaration. Do not depend on the symbol being brought in transitively via headers not directly included. One exception is if Foo is used in myfile.cc, it's ok to #include (or forward-declare) Foo in myfile.h,
inst
ead of myfile.cc. Inline Functions link ▶Define functions inline only when they are small, say, 10 lin
es
or l
es
s. Definition: You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism. Pros: Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline acc
es
sors and mutators, and other short, performance-critical functions. Cons: Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small acc
es
sor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern proc
es
sors smaller code usually runs faster due to better use of the
inst
ruction cache. Decision: A decent rule of thumb is to not inline a function if it is more than 10 lin
es
long. Beware of d
es
tructors, which are often longer than they appear because of implicit member- and base-d
es
tructor calls! Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unl
es
s, in the common case, the loop or switch statement is never executed). It is import
ant
to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the
class
, either for convenience or to document its behavior, e.g., for acc
es
sors and mutators. The -inl.h Fil
es
link ▶You may use file nam
es
with a -inl.h suffix to define complex inline functions when needed. The definition of an inline function needs to be in a header file, so that the compiler has the definition available for inlining at the call sit
es
. However, implementation code properly belongs in .cc fil
es
, and we do not like to have much actual code in .h fil
es
unl
es
s there is a readability or performance adv
ant
age. If an inline function definition is short, with very little, if any, logic in it, you should put the code in your .h file. For example, acc
es
sors and mutators should certainly be inside a
class
definition. More complex inline functions may also be put in a .h file for the convenience of the implementer and callers, though if this mak
es
the .h file too unwieldy you can
inst
ead put that code in a separate -inl.h file. This separat
es
the implementation from the
class
definition, while still allowing the implementation to be included where nec
es
sary. Another use of -inl.h fil
es
is for definitions of function templat
es
. This can be used to keep your template definitions easy to read. Do not forget that a -inl.h file requir
es
a #define guard just like any other header file. Function Parameter Ordering link ▶When defining a function, parameter order is: inputs, then outputs. Parameters to C/C++ functions are either input to the function, output from the function, or both. Input parameters are usually valu
es
or const referenc
es
, while output and input/output parameters will be non-const pointers. When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters. This is not a hard-and-fast rule. Parameters that are both input and output (often
class
es
/structs) muddy the waters, and, as always, consistency with related functions may require you to bend the rule. Nam
es
and Order of Includ
es
link ▶Use standard order for readability and to avoid hidden dependenci
es
: C library, C++ library, other librari
es
' .h, your project's .h. All of a project's header fil
es
should be listed as d
es
cent
ant
s of the project's source directory without use of UNIX directory shortcuts . (the current directory) or .. (the parent directory). For example, google-aw
es
ome-project/src/base/logging.h should be included as #include "base/logging.h" In dir/foo.cc, whose main purpose is to implement or t
es
t the stuff in dir2/foo2.h, order your includ
es
as follows: dir2/foo2.h (preferred location — see details below). C system fil
es
. C++ system fil
es
. Other librari
es
' .h fil
es
. Your project's .h fil
es
. The preferred ordering reduc
es
hidden dependenci
es
. We w
ant
every header file to be compilable on its own. The easi
es
t way to achieve this is to make sure that every one of them is the first .h file #included in some .cc. dir/foo.cc and dir2/foo2.h are often in the same directory (e.g. base/basictyp
es
_t
es
t.cc and base/basictyp
es
.h), but can be in different directori
es
too. Within each section it is nice to order the includ
es
alphabetically. For example, the includ
es
in google-aw
es
ome-project/src/foo/internal/fooserver.cc might look like this: #include "foo/public/fooserver.h" // Preferred location. #include #include #include #include #include "base/basictyp
es
.h" #include "base/commandlineflags.h" #include "foo/public/bar.h" Scoping Nam
es
pac
es
link ▶Unnamed nam
es
pac
es
in .cc fil
es
are encouraged. With named nam
es
pac
es
, choose the name based on the project, and possibly its path. Do not use a using-directive. Definition: Nam
es
pac
es
subdivide the global scope into distinct, named scop
es
, and so are useful for preventing name collisions in the global scope. Pros: Nam
es
pac
es
provide a (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by
class
es
. For example, if two different projects have a
class
Foo in the global scope, th
es
e symbols may collide at compile time or at runtime. If each project plac
es
their code in a nam
es
pace, project1::Foo and project2::Foo are now distinct symbols that do not collide. Cons: Nam
es
pac
es
can be confusing, because they provide an additional (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by
class
es
. Use of unnamed spac
es
in header fil
es
can easily cause violations of the C++ One Definition Rule (ODR). Decision: Use nam
es
pac
es
according to the policy d
es
cribed below. Unnamed Nam
es
pac
es
Unnamed nam
es
pac
es
are allowed and even encouraged in .cc fil
es
, to avoid runtime naming conflicts: nam
es
pace { // This is in a .cc file. // The content of a nam
es
pace is not indented enum { kUnused, kEOF, kError }; // Commonly used tokens. bool AtEof() { return pos_ == kEOF; } // Us
es
our nam
es
pace's EOF. } // nam
es
pace However, file-scope declarations that are assoc
iated
with a particular
class
may be declared in that
class
as typ
es
, static data members or static member functions rather than as members of an unnamed nam
es
pace. Terminate the unnamed nam
es
pace as shown, with a comment // nam
es
pace. Do not use unnamed nam
es
pac
es
in .h fil
es
. Named Nam
es
pac
es
Named nam
es
pac
es
should be used as follows: Nam
es
pac
es
wrap the entire source file after includ
es
, gflags definitions/declarations, and forward declarations of
class
es
from other nam
es
pac
es
: // In the .h file nam
es
pace mynam
es
pace { // All declarations are within the nam
es
pace scope. // Notice the lack of indentation.
class
My
Class
{ public: ... void Foo(); }; } // nam
es
pace mynam
es
pace // In the .cc file nam
es
pace mynam
es
pace { // Definition of functions is within scope of the nam
es
pace. void My
Class
::Foo() { ... } } // nam
es
pace mynam
es
pace The typical .cc file might have more complex detail, including the need to reference
class
es
in other nam
es
pac
es
. #include "a.h" DEFINE_bool(someflag, false, "dummy flag");
class
C; // Forward declaration of
class
C in the global nam
es
pace. nam
es
pace a {
class
A; } // Forward declaration of a::A. nam
es
pace b { ...code for b... // Code go
es
aga
inst
the left margin. } // nam
es
pace b Do not declare anything in nam
es
pace std, not even forward declarations of standard library
class
es
. Declaring entiti
es
in nam
es
pace std is undefined behavior, i.e., not portable. To declare entiti
es
from the standard library, include the appropriate header file. You may not use a using-directive to make all nam
es
from a nam
es
pace available. // Forbidden -- This pollut
es
the nam
es
pace. using nam
es
pace foo; You may use a using-declaration anywhere in a .cc file, and in functions, methods or
class
es
in .h fil
es
. // OK in .cc fil
es
. // Must be in a function, method or
class
in .h fil
es
. using ::foo::bar; Nam
es
pace alias
es
are allowed anywhere in a .cc file, anywhere inside the named nam
es
pace that wraps an entire .h file, and in functions and methods. // Shorten acc
es
s to some commonly used nam
es
in .cc fil
es
. nam
es
pace fbz = ::foo::bar::baz; // Shorten acc
es
s to some commonly used nam
es
(in a .h file). nam
es
pace librarian { // The
following
alias is available to all fil
es
including // this header (in nam
es
pace librarian): // alias nam
es
should therefore be chosen consistently // within a project. nam
es
pace pd_s = ::pipeline_diagnostics::sidetable; inline void my_inline_function() { // nam
es
pace alias local to a function (or method). nam
es
pace fbz = ::foo::bar::baz; ... } } // nam
es
pace librarian Note that an alias in a .h file is visible to everyone #including that file, so public headers (those available outside a project) and headers transitively #included by them, should avoid defining alias
es
, as part of the general goal of keeping public
API
s as small as possible. N
es
ted
Class
es
link ▶Although you may use public n
es
ted
class
es
when they are part of an interface, consider a nam
es
pace to keep declarations out of the global scope. Definition: A
class
can define another
class
within it; this is also called a member
class
.
class
Foo { private: // Bar is a member
class
, n
es
ted within Foo.
class
Bar { ... }; }; Pros: This is useful when the n
es
ted (or member)
class
is only used by the enclosing
class
; making it a member puts it in the enclosing
class
scope rather than polluting the outer scope with the
class
name. N
es
ted
class
es
can be forward declared within the enclosing
class
and then defined in the .cc file to avoid including the n
es
ted
class
definition in the enclosing
class
declaration, since the n
es
ted
class
definition is usually only relev
ant
to the implementation. Cons: N
es
ted
class
es
can be forward-declared only within the definition of the enclosing
class
. Thus, any header file manipulating a Foo::Bar* pointer will have to include the full
class
declaration for Foo. Decision: Do not make n
es
ted
class
es
public unl
es
s they are actually part of the interface, e.g., a
class
that holds a set of options for some method. Nonmember, Static Member, and Global Functions link ▶Prefer nonmember functions within a nam
es
pace or static member functions to global functions; use completely global functions rarely. Pros: Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a nam
es
pace avoids polluting the global nam
es
pace. Cons: Nonmember and static member functions may make more sense as members of a new
class
,
es
pecially if they acc
es
s external r
es
ourc
es
or have signific
ant
dependenci
es
. Decision: Sometim
es
it is useful, or even nec
es
sary, to define a function not bound to a
class
inst
ance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variabl
es
, and should nearly always exist in a nam
es
pace. Rather than creating
class
es
only to group static member functions which do not share static data, use nam
es
pac
es
inst
ead. Functions defined in the same compilation unit as production
class
es
may introduce unnec
es
sary coupling and link-time dependenci
es
when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new
class
, or placing the functions in a nam
es
pace possibly in a separate library. If you must define a nonmember function and it is only needed in its .cc file, use an unnamed nam
es
pace or static linkage (eg static int Foo() {...}) to limit its scope. Local Variabl
es
link ▶Place a function's variabl
es
in the narrow
es
t scope possible, and initialize variabl
es
in the declaration. C++ allows you to declare variabl
es
anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This mak
es
it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization should be used
inst
ead of declaration and assignment, e.g. int i; i = f(); // Bad -- initialization separate from declaration. int j = g(); // Good -- declaration has initialization. Note that gcc implements for (int i = 0; i < 10; ++i) correctly (the scope of i is only the scope of the for loop), so you can then reuse i in another for loop in the same scope. It also correctly scop
es
declarations in if and while statements, e.g. while (const char* p = strchr(str, '/')) str = p + 1; There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its d
es
tructor is invoked every time it go
es
out of scope. // Inefficient implementation: for (int i = 0; i < 1000000; ++i) { Foo f; // My ctor and dtor get called 1000000 tim
es
each. f.DoSomething(i); } It may be more efficient to declare such a variable used in a loop outside that loop: Foo f; // My ctor and dtor get called once each. for (int i = 0; i < 1000000; ++i) { f.DoSomething(i); } Static and Global Variabl
es
link ▶Static or global variabl
es
of
class
type are forbidden: they cause hard-to-find bugs due to indeterminate order of construction and d
es
truction. Objects with static storage duration, including global variabl
es
, static variabl
es
, static
class
member variabl
es
, and function static variabl
es
, must be Plain Old Data (POD): only ints, chars, floats, or pointers, or arrays/structs of POD. The order in which
class
constructors and initializers for static variabl
es
are called is only partially specified in C++ and can even change from build to build, which can cause bugs that are difficult to find. Therefore in addition to banning globals of
class
type, we do not allow static POD variabl
es
to be initialized with the r
es
ult of a function, unl
es
s that function (such as getenv(), or getpid()) do
es
not itself depend on any other globals. Likewise, the order in which d
es
tructors are called is defined to be the reverse of the order in which the constructors were called. Since constructor order is indeterminate, so is d
es
tructor order. For example, at program-end time a static variable might have been d
es
troyed, but code still running -- perhaps in another thread -- tri
es
to acc
es
s it and fails. Or the d
es
tructor for a static 'string' variable might be run prior to the d
es
tructor for another variable that contains a reference to that string. As a r
es
ult we only allow static variabl
es
to contain POD data. This rule completely disallows vector (use C arrays
inst
ead), or string (use const char []). If you need a static or global variable of a
class
type, consider initializing a pointer (which will never be freed), from either your main() function or from pthread_once(). Note that this must be a raw pointer, not a "smart" pointer, since the smart pointer's d
es
tructor will have the order-of-d
es
tructor issue that we are trying to avoid.
Class
es
Class
es
are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a
class
. Doing Work in Constructors link ▶In general, constructors should merely set member variabl
es
to their initial valu
es
. Any complex initialization should go in an explicit Init() method. Definition: It is possible to perform initialization in the body of the constructor. Pros: Convenience in typing. No need to worry about whether the
class
has been initialized or not. Cons: The problems with doing work in constructors are: There is no easy way for constructors to signal errors, short of using exceptions (which are forbidden). If the work fails, we now have an object whose initialization code failed, so it may be an indeterminate state. If the work calls virtual functions, th
es
e calls will not get dispatched to the sub
class
implementations. Future modification to your
class
can quietly introduce this problem even if your
class
is not currently sub
class
ed, causing much confusion. If someone creat
es
a global variable of this type (which is aga
inst
the rul
es
, but still), the constructor code will be called before main(), possibly breaking some implicit assumptions in the constructor code. For
inst
ance, gflags will not yet have been initialized. Decision: If your object requir
es
non-trivial initialization, consider having an explicit Init() method. In particular, constructors should not call virtual functions, attempt to raise errors, acc
es
s potentially uninitialized global variabl
es
, etc. Default Constructors link ▶You must define a default constructor if your
class
defin
es
member variabl
es
and has no other constructors. Otherwise the compiler will do it for you, badly. Definition: The default constructor is called when we new a
class
object with no arguments. It is always called when calling new[] (for arrays). Pros: Initializing structur
es
by default, to hold "impossible" valu
es
, mak
es
debugging much easier. Cons: Extra work for you, the code writer. Decision: If your
class
defin
es
member variabl
es
and has no other constructors you must define a default constructor (one that tak
es
no arguments). It should preferably initialize the object in such a way that its internal state is consistent and valid. The reason for this is that if you have no other constructors and do not define a default constructor, the compiler will generate one for you. This compiler generated constructor may not initialize your object sensibly. If your
class
inherits from an existing
class
but you add no new member variabl
es
, you are not required to have a default constructor. Explicit Constructors link ▶Use the C++ keyword explicit for constructors with one argument. Definition: Normally, if a constructor tak
es
one argument, it can be used as a conversion. For
inst
ance, if you define Foo::Foo(string name) and then pass a string to a function that expects a Foo, the constructor will be called to convert the string into a Foo and will pass the Foo to your function for you. This can be convenient but is also a source of trouble when things get converted and new objects created without you meaning them to. Declaring a constructor explicit prevents it from being invoked implicitly as a conversion. Pros: Avoids und
es
irable conversions. Cons: None. Decision: We require all single argument constructors to be explicit. Always put explicit in front of one-argument constructors in the
class
definition: explicit Foo(string name); The exception is copy constructors, which, in the rare cas
es
when we allow them, should probably not be explicit.
Class
es
that are intended to be transparent wrappers around other
class
es
are also exceptions. Such exceptions should be clearly marked with comments. Copy Constructors link ▶Provide a copy constructor and assignment operator only when nec
es
sary. Otherwise, disable them with DISALLOW_COPY_AND_ASSIGN. Definition: The copy constructor and assignment operator are used to create copi
es
of objects. The copy constructor is implicitly invoked by the compiler in some situations, e.g. passing objects by value. Pros: Copy constructors make it easy to copy objects. STL containers require that all contents be copyable and assignable. Copy constructors can be more efficient than CopyFrom()-style workarounds because they combine construction with copying, the compiler can elide them in some contexts, and they make it easier to avoid heap allocation. Cons: Implicit copying of objects in C++ is a rich source of bugs and of performance problems. It also reduc
es
readability, as it becom
es
hard to track which objects are being passed around by value as opposed to by reference, and therefore where chang
es
to an object are reflected. Decision: Few
class
es
need to be copyable. Most should have neither a copy constructor nor an assignment operator. In many situations, a pointer or reference will work just as well as a copied value, with better performance. For example, you can pass function parameters by reference or pointer
inst
ead of by value, and you can store pointers rather than objects in an STL container. If your
class
needs to be copyable, prefer providing a copy method, such as CopyFrom() or Clone(), rather than a copy constructor, because such methods cannot be invoked implicitly. If a copy method is insufficient in your situation (e.g. for performance reasons, or because your
class
needs to be stored by value in an STL container), provide both a copy constructor and assignment operator. If your
class
do
es
not need a copy constructor or assignment operator, you must explicitly disable them. To do so, add dummy declarations for the copy constructor and assignment operator in the private: section of your
class
, but do not provide any corr
es
ponding definition (so that any attempt to use them r
es
ults in a link error). For convenience, a DISALLOW_COPY_AND_ASSIGN macro can be used: // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a
class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) Then, in
class
Foo:
class
Foo { public: Foo(int f); ~Foo(); private: DISALLOW_COPY_AND_ASSIGN(Foo); }; Structs vs.
Class
es
link ▶Use a struct only for passive objects that carry data; everything else is a
class
. The struct and
class
keywords behave almost identically in C++. We add our own sem
ant
ic meanings to each keyword, so you should use the appropriate keyword for the data-type you're defining. structs should be used for passive objects that carry data, and may have assoc
iated
const
ant
s, but lack any functionality other than acc
es
s/setting the data members. The acc
es
sing/setting of fields is done by directly acc
es
sing the fields rather than through method invocations. Methods should not provide behavior but should only be used to set up the data members, e.g., constructor, d
es
tructor, Initialize(), R
es
et(), Validate(). If more functionality is required, a
class
is more appropriate. If in doubt, make it a
class
. For consistency with STL, you can use struct
inst
ead of
class
for functors and traits. Note that member variabl
es
in structs and
class
es
have different naming rul
es
. Inheritance link ▶Composition is often more appropriate than inheritance. When using inheritance, make it public. Definition: When a sub-
class
inherits from a base
class
, it includ
es
the definitions of all the data and operations that the parent base
class
defin
es
. In practice, inheritance is used in two major ways in C++: implementation inheritance, in which actual code is inherited by the child, and interface inheritance, in which only method nam
es
are inherited. Pros: Implementation inheritance reduc
es
code size by re-using the base
class
code as it specializ
es
an existing type. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a
class
expose a particular
API
. Again, the compiler can detect errors, in this case, when a
class
do
es
not define a nec
es
sary method of the
API
. Cons: For implementation inheritance, because the code implementing a sub-
class
is spread between the base and the sub-
class
, it can be more difficult to understand an implementation. The sub-
class
cannot override functions that are not virtual, so the sub-
class
cannot change implementation. The base
class
may also define some data members, so that specifi
es
physical layout of the base
class
. Decision: All inheritance should be public. If you w
ant
to do private inheritance, you should be including an
inst
ance of the base
class
as a member
inst
ead. Do not overuse implementation inheritance. Composition is often more appropriate. Try to r
es
trict use of inheritance to the "is-a" case: Bar sub
class
es
Foo if it can reasonably be said that Bar "is a kind of" Foo. Make your d
es
tructor virtual if nec
es
sary. If your
class
has virtual methods, its d
es
tructor should be virtual. Limit the use of protected to those member functions that might need to be acc
es
sed from sub
class
es
. Note that data members should be private. When redefining an inherited virtual function, explicitly declare it virtual in the declaration of the derived
class
. Rationale: If virtual is omitted, the reader has to check all anc
es
tors of the
class
in qu
es
tion to determine if the function is virtual or not. Multiple Inheritance link ▶Only very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the base
class
es
has an implementation; all other base
class
es
must be pure interface
class
es
tagged with the Interface suffix. Definition: Multiple inheritance allows a sub-
class
to have more than one base
class
. We distinguish between base
class
es
that are pure interfac
es
and those that have an implementation. Pros: Multiple implementation inheritance may let you re-use even more code than single inheritance (see Inheritance). Cons: Only very rarely is multiple implementation inheritance actually useful. When multiple implementation inheritance seems like the solution, you can usually find a different, more explicit, and cleaner solution. Decision: Multiple inheritance is allowed only when all super
class
es
, with the possible exception of the first one, are pure interfac
es
. In order to ensure that they remain pure interfac
es
, they must end with the Interface suffix. Note: There is an exception to this rule on Windows. Interfac
es
link ▶
Class
es
that satisfy certain conditions are allowed, but not required, to end with an Interface suffix. Definition: A
class
is a pure interface if it meets the
following
requirements: It has only public pure virtual ("= 0") methods and static methods (but see below for d
es
tructor). It may not have non-static data members. It need not have any constructors defined. If a constructor is provided, it must take no arguments and it must be protected. If it is a sub
class
, it may only be derived from
class
es
that satisfy th
es
e conditions and are tagged with the Interface suffix. An interface
class
can never be directly
inst
ant
iated
because of the pure virtual method(s) it declar
es
. To make sure all implementations of the interface can be d
es
troyed correctly, they must also declare a virtual d
es
tructor (in an exception to the first rule, this should not be pure). See Stroustrup, The C++ Programming Language, 3rd edition, section 12.4 for details. Pros: Tagging a
class
with the Interface suffix lets others know that they must not add implemented methods or non static data members. This is particularly import
ant
in the case of multiple inheritance. Additionally, the interface concept is already well-understood by Java programmers. Cons: The Interface suffix lengthens the
class
name, which can make it harder to read and understand. Also, the interface property may be considered an implementation detail that shouldn't be exposed to clients. Decision: A
class
may end with Interface only if it meets the above requirements. We do not require the converse, however:
class
es
that meet the above requirements are not required to end with Interface. Operator Overloading link ▶Do not overload operators except in rare, special circumstanc
es
. Definition: A
class
can define that operators such as + and / operate on the
class
as if it were a built-in type. Pros: Can make code appear more intuitive because a
class
will behave in the same way as built-in typ
es
(such as int). Overloaded operators are more playful nam
es
for functions that are l
es
s-colorfully named, such as Equals() or Add(). For some template functions to work correctly, you may need to define operators. Cons: While operator overloading can make code more intuitive, it has several drawbacks: It can fool our intuition into thinking that expensive operations are cheap, built-in operations. It is much harder to find the call sit
es
for overloaded operators. Searching for Equals() is much easier than searching for relev
ant
invocations of ==. Some operators work on pointers too, making it easy to introduce bugs. Foo + 4 may do one thing, while &Foo + 4 do
es
something totally different. The compiler do
es
not complain for either of th
es
e, making this very hard to debug. Overloading also has surprising ramifications. For
inst
ance, if a
class
overloads unary operator&, it cannot safely be forward-declared. Decision: In general, do not overload operators. The assignment operator (operator=), in particular, is insidious and should be avoided. You can define functions like Equals() and CopyFrom() if you need them. Likewise, avoid the dangerous unary operator& at all costs, if there's any possibility the
class
might be forward-declared. However, there may be rare cas
es
where you need to overload an operator to interoperate with templat
es
or "standard" C++
class
es
(such as operator<<(ostream&, const T&) for logging). Th
es
e are acceptable if fully justified, but you should try to avoid th
es
e whenever possible. In particular, do not overload operator== or operator< just so that your
class
can be used as a key in an STL container;
inst
ead, you should create equality and comparison functor typ
es
when declaring the container. Some of the STL algorithms do require you to overload operator==, and you may do so in th
es
e cas
es
, provided you document why. See also Copy Constructors and Function Overloading. Acc
es
s Control link ▶Make data members private, and provide acc
es
s to them through acc
es
sor functions as needed (for technical reasons, we allow data members of a t
es
t fixture
class
to be protected when using Google T
es
t). Typically a variable would be called foo_ and the acc
es
sor function foo(). You may also w
ant
a mutator function set_foo(). Exception: static const data members (typically called kFoo) need not be private. The definitions of acc
es
sors are usually inlined in the header file. See also Inheritance and Function Nam
es
. Declaration Order link ▶Use the specified order of declarations within a
class
: public: before private:, methods before data members (variabl
es
), etc. Your
class
definition should start with its public: section, followed by its protected: section and then its private: section. If any of th
es
e sections are empty, omit them. Within each section, the declarations generally should be in the
following
order: Typedefs and Enums Const
ant
s (static const data members) Constructors D
es
tructor Methods, including static methods Data Members (except static const data members) Friend declarations should always be in the private section, and the DISALLOW_COPY_AND_ASSIGN macro invocation should be at the end of the private: section. It should be the last thing in the
class
. See Copy Constructors. Method definitions in the corr
es
ponding .cc file should be the same as the declaration order, as much as possible. Do not put large method definitions inline in the
class
definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline. See Inline Functions for more details. Write Short Functions link ▶Prefer small and focused functions. We recognize that long functions are sometim
es
appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lin
es
, think about whether it can be broken up without harming the structure of the program. Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could r
es
ult in bugs that are hard to find. Keeping your functions short and simple mak
es
it easier for other people to read and modify your code. You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function prov
es
to be difficult, you find that errors are hard to debug, or you w
ant
to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable piec
es
. Google-Specific Magic There are various tricks and utiliti
es
that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere. Smart Pointers link ▶If you actually need pointer sem
ant
ics, scoped_ptr is great. You should only use std::tr1::shared_ptr under very specific conditions, such as when objects need to be held by STL containers. You should never use auto_ptr. "Smart" pointers are objects that act like pointers but have added sem
ant
ics. When a scoped_ptr is d
es
troyed, for
inst
ance, it delet
es
the object it's pointing to. shared_ptr is the same way, but implements reference-counting so only the last pointer to an object delet
es
it. Generally speaking, we prefer that we d
es
ign code with clear object ownership. The clear
es
t object ownership is obtained by using an object directly as a field or local variable, without using pointers at all. On the other extreme, by their very definition, reference counted pointers are owned by nobody. The problem with this d
es
ign is that it is easy to create circular referenc
es
or other strange conditions that cause an object to never be deleted. It is also slow to perform atomic operations every time a value is copied or assigned. Although they are not recommended, reference counted pointers are sometim
es
the simpl
es
t and most eleg
ant
way to solve a problem. cpplint link ▶Use cpplint.py to detect style errors. cpplint.py is a tool that reads a source file and identifi
es
many style errors. It is not perfect, and has both false positiv
es
and false negativ
es
, but it is still a valuable tool. False positiv
es
can be ignored by putting // NOLINT at the end of the line. Some projects have
inst
ructions on how to run cpplint.py from their project tools. If the project you are contributing to do
es
not, you can download cpplint.py separately. Other C++ Featur
es
Reference Arguments link ▶All parameters passed by reference must be labeled const. Definition: In C, if a function needs to modify a variable, the parameter must use a pointer, eg int foo(int *pval). In C++, the function can alternatively declare a reference parameter: int foo(int &val). Pros: Defining a parameter as reference avoids ugly code like (*pval)++. Nec
es
sary for some applications like copy constructors. Mak
es
it clear, unlike with pointers, that NULL is not a possible value. Cons: Referenc
es
can be confusing, as they have value syntax but pointer sem
ant
ics. Decision: Within function parameter lists all referenc
es
must be const: void Foo(const string &in, string *out); In fact it is a very strong convention in Google code that input arguments are valu
es
or const referenc
es
while output arguments are pointers. Input parameters may be const pointers, but we never allow non-const reference parameters. One case when you might w
ant
an input parameter to be a const pointer is if you w
ant
to emphasize that the argument is not copied, so it must exist for the lifetime of the object; it is usually b
es
t to document this in comments as well. STL adapters such as bind2nd and mem_fun do not permit reference parameters, so you must declare functions with pointer parameters in th
es
e cas
es
, too. Function Overloading link ▶Use overloaded functions (including constructors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called. Definition: You may write a function that tak
es
a const string& and overload it with another that tak
es
const char*.
class
My
Class
{ public: void Analyze(const string &text); void Analyze(const char *text, size_t textlen); }; Pros: Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be nec
es
sary for templatized code, and it can be convenient for Visitors. Cons: If a function is overloaded by the argument typ
es
alone, a reader may have to understand C++'s complex matching rul
es
in order to tell what's going on. Also many people are confused by the sem
ant
ics of inheritance if a derived
class
overrid
es
only some of the vari
ant
s of a function. Decision: If you w
ant
to overload a function, consider qualifying the name with some information about the arguments, e.g., AppendString(), AppendInt() rather than just Append(). Default Arguments link ▶We do not allow default function parameters, except in a few uncommon situations explained below. Pros: Often you have a function that us
es
lots of default valu
es
, but occasionally you w
ant
to override the defaults. Default parameters allow an easy way to do this without having to define many functions for the rare exceptions. Cons: People often figure out how to use an
API
by looking at existing code that us
es
it. Default parameters are more difficult to maintain because copy-and-paste from previous code may not reveal all the parameters. Copy-and-pasting of code segments can cause major problems when the default arguments are not appropriate for the new code. Decision: Except as d
es
cribed below, we require all arguments to be explicitly specified, to force programmers to consider the
API
and the valu
es
they are passing for each argument rather than silently accepting defaults they may not be aware of. One specific exception is when default arguments are used to simulate variable-length argument lists. // Support up to 4 params by using a default empty AlphaNum. string StrCat(const AlphaNum &a, const AlphaNum &b = gEmptyAlphaNum, const AlphaNum &c = gEmptyAlphaNum, const AlphaNum &d = gEmptyAlphaNum); Variable-Length Arrays and alloca() link ▶We do not allow variable-length arrays or alloca(). Pros: Variable-length arrays have natural-looking syntax. Both variable-length arrays and alloca() are very efficient. Cons: Variable-length arrays and alloca are not part of Standard C++. More import
ant
ly, they allocate a data-dependent amount of stack space that can trigger difficult-to-find memory overwriting bugs: "It ran fine on my machine, but di
es
mysteriously in production". Decision: Use a safe allocator
inst
ead, such as scoped_ptr/scoped_array. Friends link ▶We allow use of friend
class
es
and functions, within reason. Friends should usually be defined in the same file so that the reader do
es
not have to look in another file to find us
es
of the private members of a
class
. A common use of friend is to have a FooBuilder
class
be a friend of Foo so that it can construct the inner state of Foo correctly, without exposing this state to the world. In some cas
es
it may be useful to make a unitt
es
t
class
a friend of the
class
it t
es
ts. Friends extend, but do not break, the encapsulation boundary of a
class
. In some cas
es
this is better than making a member public when you w
ant
to give only one other
class
acc
es
s to it. However, most
class
es
should interact with other
class
es
solely through their public members. Exceptions link ▶We do not use C++ exceptions. Pros: Exceptions allow higher levels of an application to decide how to handle "can't happen" failur
es
in deeply n
es
ted functions, without the obscuring and error-prone bookkeeping of error cod
es
. Exceptions are used by most other modern languag
es
. Using them in C++ would make it more consistent with Python, Java, and the C++ that others are familiar with. Some third-party C++ librari
es
use exceptions, and turning them off internally mak
es
it harder to integrate with those librari
es
. Exceptions are the only way for a constructor to fail. We can simulate this with a factory function or an Init() method, but th
es
e require heap allocation or a new "invalid" state, r
es
pectively. Exceptions are really handy in t
es
ting frameworks. Cons: When you add a throw statement to an existing function, you must examine all of its transitive callers. Either they must make at least the basic exception safety guar
ant
ee, or they must never catch the exception and be happy with the program terminating as a r
es
ult. For
inst
ance, if f() calls g() calls h(), and h throws an exception that f catch
es
, g has to be careful or it may not clean up properly. More generally, exceptions make the control flow of programs difficult to evaluate by looking at code: functions may return in plac
es
you don't expect. This caus
es
maintainability and debugging difficulti
es
. You can minimize this cost via some rul
es
on how and where exceptions can be used, but at the cost of more that a developer needs to know and understand. Exception safety requir
es
both RAII and different coding practic
es
. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid requiring readers to understand the entire call graph, exception-safe code must isolate logic that writ
es
to persistent state into a "commit" phase. This will have both benefits and costs (perhaps where you're forced to obfuscate code to isolate the commit). Allowing exceptions would force us to always pay those costs even when they're not worth it. Turning on exceptions adds data to each binary produced, increasing compile time (probably slightly) and possibly increasing addr
es
s space pr
es
sure. The availability of exceptions may encourage developers to throw them when they are not appropriate or recover from them when it's not safe to do so. For example, invalid user input should not cause exceptions to be thrown. We would need to make the style guide even longer to document th
es
e r
es
trictions! Decision: On their face, the benefits of using exceptions outweigh the costs,
es
pecially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becom
es
problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generat
es
exceptions. Given that Google's existing code is not exception-toler
ant
, the costs of using exceptions are somewhat greater than the costs in a new project. The conversion proc
es
s would be slow and error-prone. We don't believe that the available alternativ
es
to exceptions, such as error cod
es
and assertions, introduce a signific
ant
burden. Our advice aga
inst
using exceptions is not predicated on philosophical or moral grounds, but practical on
es
. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise aga
inst
exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch. There is an exception to this rule (no pun intended) for Windows code. Run-Time Type Information (RTTI) link ▶We do not use Run Time Type Information (RTTI). Definition: RTTI allows a programmer to query the C++
class
of an object at run time. Pros: It is useful in some unitt
es
ts. For example, it is useful in t
es
ts of factory
class
es
where the t
es
t has to verify that a newly created object has the expected dynamic type. In rare circumstanc
es
, it is useful even outside of t
es
ts. Cons: A query of type during run-time typically means a d
es
ign problem. If you need to know the type of an object at runtime, that is often an indication that you should reconsider the d
es
ign of your
class
. Decision: Do not use RTTI, except in unitt
es
ts. If you find yourself in need of writing code that behav
es
differently based on the
class
of an object, consider one of the alternativ
es
to querying the type. Virtual methods are the preferred way of executing different code paths depending on a specific sub
class
type. This puts the work within the object itself. If the work belongs outside the object and
inst
ead in some proc
es
sing code, consider a double-dispatch solution, such as the Visitor d
es
ign pattern. This allows a facility outside the object itself to determine the type of
class
using the built-in type system. If you think you truly cannot use those ideas, you may use RTTI. But think twice about it. :-) Then think twice again. Do not hand-implement an RTTI-like workaround. The arguments aga
inst
RTTI apply just as much to workarounds like
class
hierarchi
es
with type tags. Casting link ▶Use C++ casts like static_cast(). Do not use other cast formats like int y = (int)x; or int y = int(x);. Definition: C++ introduced a different cast system from C that distinguish
es
the typ
es
of cast operations. Pros: The problem with C casts is the ambiguity of the operation; sometim
es
you are doing a conversion (e.g., (int)3.5) and sometim
es
you are doing a cast (e.g., (int)"hello"); C++ casts avoid this. Additionally C++ casts are more visible when searching for them. Cons: The syntax is nasty. Decision: Do not use C-style casts.
Inst
ead, use th
es
e C++-style casts. Use static_cast as the equivalent of a C-style cast that do
es
value conversion, or when you need to explicitly up-cast a pointer from a
class
to its super
class
. Use const_cast to remove the const qualifier (see const). Use reinterpret_cast to do unsafe conversions of pointer typ
es
to and from integer and other pointer typ
es
. Use this only if you know what you are doing and you understand the aliasing issu
es
. Do not use dynamic_cast except in t
es
t code. If you need to know type information at runtime in this way outside of a unitt
es
t, you probably have a d
es
ign flaw. Streams link ▶Use streams only for logging. Definition: Streams are a replacement for printf() and scanf(). Pros: With streams, you do not need to know the type of the object you are printing. You do not have problems with format strings not matching the argument list. (Though with gcc, you do not have that problem with printf either.) Streams have automatic constructors and d
es
tructors that open and close the relev
ant
fil
es
. Cons: Streams make it difficult to do functionality like pread(). Some formatting (particularly the common format string idiom %.*s) is difficult if not impossible to do efficiently using streams without using printf-like hacks. Streams do not support operator reordering (the %1s directive), which is helpful for internationalization. Decision: Do not use streams, except where required by a logging interface. Use printf-like routin
es
inst
ead. There are various pros and cons to using streams, but in this case, as in many other cas
es
, consistency trumps the debate. Do not use streams in your code. Extended Discussion There has been debate on this issue, so this explains the reasoning in greater depth. Recall the Only One Way guiding principle: we w
ant
to make sure that whenever we do a certain type of I/O, the code looks the same in all those plac
es
. Because of this, we do not w
ant
to allow users to decide between using streams or using printf plus Read/Write/etc.
Inst
ead, we should settle on one or the other. We made an exception for logging because it is a pretty specialized application, and for historical reasons. Proponents of streams have argued that streams are the obvious choice of the two, but the issue is not actually so clear. For every adv
ant
age of streams they point out, there is an equivalent disadv
ant
age. The bigg
es
t adv
ant
age is that you do not need to know the type of the object to be printing. This is a fair point. But, there is a downside: you can easily use the wrong type, and the compiler will not warn you. It is easy to make this kind of mistake without knowing when using streams. cout << this; // Prints the addr
es
s cout << *this; // Prints the contents The compiler do
es
not generate an error because << has been overloaded. We discourage overloading for just this reason. Some say printf formatting is ugly and hard to read, but streams are often no better. Consider the
following
two fragments, both with the same typo. Which is easier to discover? cerr << "Error connecting to '"
hostname.first << ":"
hostname.second << ": "
hostname.first, foo->bar()->hostname.second, strerror(errno)); And so on and so forth for any issue you might bring up. (You could argue, "Things would be better with the right wrappers," but if it is true for one scheme, is it not also true for the other? Also, remember the goal is to make the language smaller, not add yet more machinery that someone has to learn.) Either path would yield different adv
ant
ag
es
and disadv
ant
ag
es
, and there is not a clearly superior solution. The simplicity doctrine mandat
es
we settle on one of them though, and the majority decision was on printf + read/write. Preincrement and Predecrement link ▶Use prefix form (++i) of the increment and decrement operators with iterators and other template objects. Definition: When a variable is incremented (++i or i++) or decremented (--i or i--) and the value of the expr
es
sion is not used, one must decide whether to preincrement (decrement) or postincrement (decrement). Pros: When the return value is ignored, the "pre" form (++i) is never l
es
s efficient than the "post" form (i++), and is often more efficient. This is because post-increment (or decrement) requir
es
a copy of i to be made, which is the value of the expr
es
sion. If i is an iterator or other non-scalar type, copying i could be expensive. Since the two typ
es
of increment behave the same when the value is ignored, why not just always pre-increment? Cons: The tradition developed, in C, of using post-increment when the expr
es
sion value is not used,
es
pecially in for loops. Some find post-increment easier to read, since the "subject" (i) preced
es
the "verb" (++), just like in English. Decision: For simple scalar (non-object) valu
es
there is no reason to prefer one form and we allow either. For iterators and other template typ
es
, use pre-increment. Use of const link ▶We strongly recommend that you use const whenever it mak
es
sense to do so. Definition: Declared variabl
es
and parameters can be preceded by the keyword const to indicate the variabl
es
are not changed (e.g., const int foo).
Class
functions can have the const qualifier to indicate the function do
es
not change the state of the
class
member variabl
es
(e.g.,
class
Foo { int Bar(char c) const; };). Pros: Easier for people to understand how variabl
es
are being used. Allows the compiler to do better type checking, and, conceivably, generate better code. Helps people convince themselv
es
of program correctn
es
s because they know the functions they call are limited in how they can modify your variabl
es
. Helps people know what functions are safe to use without locks in multi-threaded programs. Cons: const is viral: if you pass a const variable to a function, that function must have const in its prototype (or the variable will need a const_cast). This can be a particular problem when calling library functions. Decision: const variabl
es
, data members, methods and arguments add a level of compile-time type checking; it is better to detect errors as soon as possible. Therefore we strongly recommend that you use const whenever it mak
es
sense to do so: If a function do
es
not modify an argument passed by reference or by pointer, that argument should be const. Declare methods to be const whenever possible. Acc
es
sors should almost always be const. Other methods should be const if they do not modify any data members, do not call any non-const methods, and do not return a non-const pointer or non-const reference to a data member. Consider making data members const whenever they do not need to be modified after construction. However, do not go crazy with const. Something like const int * const * const x; is likely overkill, even if it accurately d
es
crib
es
how const x is. Focus on what's really useful to know: in this case, const int** x is probably sufficient. The mutable keyword is allowed but is unsafe when used with threads, so thread safety should be carefully considered first. Where to put the const Some people favor the form int const *foo to const int* foo. They argue that this is more readable because it's more consistent: it keeps the rule that const always follows the object it's d
es
cribing. However, this consistency argument do
es
n't apply in this case, because the "don't go crazy" dictum eliminat
es
most of the us
es
you'd have to be consistent with. Putting the const first is arguably more readable, since it follows English in putting the "adjective" (const) before the "noun" (int). That said, while we encourage putting const first, we do not require it. But be consistent with the code around you! Integer Typ
es
link ▶Of the built-in C++ integer typ
es
, the only one used is int. If a program needs a variable of a different size, use a precise-width integer type from , such as int16_t. Definition: C++ do
es
not specify the siz
es
of its integer typ
es
. Typically people assume that short is 16 bits, int is 32 bits, long is 32 bits and long long is 64 bits. Pros: Uniformity of declaration. Cons: The siz
es
of integral typ
es
in C++ can vary based on compiler and architecture. Decision: defin
es
typ
es
like int16_t, uint32_t, int64_t, etc. You should always use those in preference to short, unsigned long long and the like, when you need a guar
ant
ee on the size of an integer. Of the C integer typ
es
, only int should be used. When appropriate, you are welcome to use standard typ
es
like size_t and ptrdiff_t. We use int very often, for integers we know are not going to be too big, e.g., loop counters. Use plain old int for such things. You should assume that an int is at least 32 bits, but don't assume that it has more than 32 bits. If you need a 64-bit integer type, use int64_t or uint64_t. For integers we know can be "big", use int64_t. You should not use the unsigned integer typ
es
such as uint32_t, unl
es
s the qu
ant
ity you are repr
es
enting is really a bit pattern rather than a number, or unl
es
s you need defined twos-complement overflow. In particular, do not use unsigned typ
es
to say a number will never be negative.
Inst
ead, use assertions for this. On Unsigned Integers Some people, including some textbook authors, recommend using unsigned typ
es
to repr
es
ent numbers that are never negative. This is intended as a form of self-documentation. However, in C, the adv
ant
ag
es
of such documentation are outweighed by the real bugs it can introduce. Consider: for (unsigned int i = foo.Length()-1; i >= 0; --i) ... This code will never terminate! Sometim
es
gcc will notice this bug and warn you, but often it will not. Equally bad bugs can occur when comparing signed and unsigned variabl
es
. Basically, C's type-promotion scheme caus
es
unsigned typ
es
to behave differently than one might expect. So, document that a variable is non-negative using assertions. Don't use an unsigned type. 64-bit Portability link ▶Code should be 64-bit and 32-bit friendly. Bear in mind problems of printing, comparisons, and structure alignment. printf() specifiers for some typ
es
are not cleanly portable between 32-bit and 64-bit systems. C99 defin
es
some portable format specifiers. Unfortunately, MSVC 7.1 do
es
not understand some of th
es
e specifiers and the standard is missing a few, so we have to define our own ugly versions in some cas
es
(in the style of the standard include file inttyp
es
.h): // printf macros for size_t, in the style of inttyp
es
.h #ifdef _LP64 #define __PRIS_PREFIX "z" #else #define __PRIS_PREFIX #endif // Use th
es
e macros after a % in a printf format string // to get correct 32/64 bit behavior, like this: // size_t size = records.size(); // printf("%"PRIuS"\n", size); #define PRIdS __PRIS_PREFIX "d" #define PRIxS __PRIS_PREFIX "x" #define PRIuS __PRIS_PREFIX "u" #define PRIXS __PRIS_PREFIX "X" #define PRIoS __PRIS_PREFIX "o" Type DO NOT use DO use Not
es
void * (or any pointer) %lx %p int64_t %qd, %lld %"PRId64" uint64_t %qu, %llu, %llx %"PRIu64", %"PRIx64" size_t %u %"PRIuS", %"PRIxS" C99 specifi
es
%zu ptrdiff_t %d %"PRIdS" C99 specifi
es
%zd Note that the PRI* macros expand to independent strings which are concatenated by the compiler. Hence if you are using a non-const
ant
format string, you need to insert the value of the macro into the format, rather than the name. It is still possible, as usual, to include length specifiers, etc., after the % when using the PRI* macros. So, e.g. printf("x = %30"PRIuS"\n", x) would expand on 32-bit Linux to printf("x = %30" "u" "\n", x), which the compiler will treat as printf("x = %30u\n", x). Remember that sizeof(void *) != sizeof(int). Use intptr_t if you w
ant
a pointer-sized integer. You may need to be careful with structure alignments, particularly for structur
es
being stored on disk. Any
class
/structure with a int64_t/uint64_t member will by default end up being 8-byte aligned on a 64-bit system. If you have such structur
es
being shared on disk between 32-bit and 64-bit code, you will need to ensure that they are packed the same on both architectur
es
. Most compilers offer a way to alter structure alignment. For gcc, you can use __attribute__((packed)). MSVC offers #pragma pack() and __declspec(align()). Use the LL or ULL suffix
es
a
微软内部资料-SQL性能优化3
Contents Overview 1 L
es
son 1: Concepts – Locks and Lock Manager 3 L
es
son 2: Concepts – Batch and Transaction 31 L
es
son 3: Concepts – Locks and Applications 51 L
es
son 4: Information Collection and Analysis 63 L
es
son 5: Concepts – Formulating and Implementing R
es
olution 81 Module 4: Troubl
es
hooting Locking and Blocking Overview At the end of this module, you will be able to: Discuss how lock manager us
es
lock mode, lock r
es
ourc
es
, and lock compatibility to achieve transaction isolation. D
es
cribe the various transaction typ
es
and how transactions differ from batch
es
. D
es
cribe how to troubl
es
hoot blocking and locking issu
es
. Analyze the output of blocking scripts and Microsoft® SQL Server™ Profiler to troubl
es
hoot locking and blocking issu
es
. Formulate hypoth
es
is to r
es
olve locking and blocking issu
es
. L
es
son 1: Concepts – Locks and Lock Manager This l
es
son outlin
es
some of the common caus
es
that contribute to the perception of a slow server. What You Will Learn After completing this l
es
son, you will be able to: D
es
cribe locking architecture used by SQL Server. Identify the various lock mod
es
used by SQL Server. Discuss lock compatibility and concurrent acc
es
s. Identify different typ
es
of lock r
es
ourc
es
. Discuss dynamic locking and lock
es
calation. Differentiate locks, latch
es
, and other SQL Server internal “locking” mechanism such as spinlocks and other synchronization objects. Recommended Reading Chapter 14 “Locking”, Inside SQL Server 2000 by Kalen Delaney SOX000821700049 – SQL 7.0 How to interpret lock r
es
ource Ids SOX000925700237 – TITLE: Lock
es
calation in SQL 7.0 SOX001109700040 – INF: Queri
es
with PREFETCH in the plan hold lock until the end of transaction Locking Concepts Delivery Tip Prior to delivering this material, t
es
t the
class
to see if they fully understand the different isolation levels. If the
class
is not confident in their understanding, review appendix A04_Locking and its accompanying PowerPoint® file. Transactions in SQL Server provide the ACID properti
es
: Atomicity A transaction either commits or aborts. If a transaction commits, all of its effects remain. If it aborts, all of its effects are undone. It is an “all or nothing” operation. Consistency An application should maintain the consistency of a database. For example, if you defer constraint checking, it is your r
es
ponsibility to ensure that the database is consistent. Isolation Concurrent transactions are isolated from the updat
es
of other incomplete transactions. Th
es
e updat
es
do not constitute a consistent state. This property is often called serializability. For example, a second transaction traversing the doubly linked list mentioned above would see the list before or after the insert, but it will see only complete chang
es
. Durability After a transaction commits, its effects will persist even if there are system failur
es
. Consistency and isolation are the most import
ant
in d
es
cribing SQL Server’s locking model. It is up to the application to define what consistency means, and isolation in some form is needed to achieve consistent r
es
ults. SQL Server us
es
locking to achieve isolation. Definition of Dependency: A set of transactions can run concurrently if their outputs are disjoint from the union of one another’s input and output sets. For example, if T1 writ
es
some object that is in T2’s input or output set, there is a dependency between T1 and T2. Bad Dependenci
es
Th
es
e include lost updat
es
, dirty reads, non-repeatable reads, and ph
ant
oms. ANSI SQL Isolation Levels An isolation level determin
es
the degree to which data is isolated for use by one proc
es
s and guarded aga
inst
interference from other proc
es
s
es
. Prior to SQL Server 7.0, REPEATABLE READ and SERIALIZABLE isolation levels were synonymous. There was no way to prevent non-repeatable reads while not preventing ph
ant
oms. By default, SQL Server 2000 operat
es
at an isolation level of READ COMMITTED. To make use of either more or l
es
s strict isolation levels in applications, locking can be customized for an entire s
es
sion by setting the isolation level of the s
es
sion with the SET TRANSACTION ISOLATION LEVEL statement. To determine the transaction isolation level currently set, use the DBCC USEROPTIONS statement, for example: USE pubs GO SET TRANSACTION ISOLATION LEVEL REPEATABLE READ GO DBCC USEROPTIONS GO Multigranular Locking Multigranular Locking In our example, if one transaction (T1) holds an exclusive lock at the table level, and another transaction (T2) holds an exclusive lock at the row level, each of the transactions believe they have exclusive acc
es
s to the r
es
ource. In this scenario, since T1 believ
es
it locks the entire table, it might inadvertently make chang
es
to the same row that T2 thought it has locked exclusively. In a multigranular locking environment, there must be a way to effectively overcome this scenario. Intent lock is the answer to this problem. Intent Lock Intent Lock is the term used to mean placing a marker in a higher-level lock queue. The type of intent lock can also be called the multigranular lock mode. An intent lock indicat
es
that SQL Server w
ant
s to acquire a shared (S) lock or exclusive (X) lock on some of the r
es
ourc
es
lower down in the hierarchy. For example, a shared intent lock placed at the table level means that a transaction intends on placing shared (S) locks on pag
es
or rows within that table. Setting an intent lock at the table level prevents another transaction from subsequently acquiring an exclusive (X) lock on the table containing that page. Intent locks improve performance because SQL Server examin
es
intent locks only at the table level to determine whether a transaction can safely acquire a lock on that table. This remov
es
the requirement to examine every row or page lock on the table to determine whether a transaction can lock the entire table. Lock Mode The code shown in the slide repr
es
ents how the lock mode is stored internally. You can see th
es
e cod
es
by querying the master.dbo.spt_valu
es
table: SELECT * FROM master.dbo.spt_valu
es
WHERE type = N'L' However, the req_mode column of master.dbo.syslockinfo has lock mode code that is one l
es
s than the code valu
es
shown here. For example, value of req_mode = 3 repr
es
ents the Shared lock mode rather than the Schema Modification lock mode. Lock Compatibility Th
es
e locks can apply at any coarser level of granularity. If a row is locked, SQL Server will apply intent locks at both the page and the table level. If a page is locked, SQL Server will apply an intent lock at the table level. SIX locks imply that we have shared acc
es
s to a r
es
ource and we have also placed X locks at a lower level in the hierarchy. SQL Server never asks for SIX locks directly, they are always the r
es
ult of a conversion. For example, suppose a transaction scanned a page using an S lock and then subsequently decided to perform a row level update. The row would obtain an X lock, but now the page would require an IX lock. The r
es
ult
ant
mode on the page would be SIX. Another type of table lock is a schema stability lock (Sch-S) and is compatible with all table locks except the schema modification lock (Sch-M). The schema modification lock (Sch-M) is incompatible with all table locks. Locking R
es
ourc
es
Delivery Tip Note the differenc
es
between Key and Key Range locks. Key Range locks will be covered in a couple of slid
es
. SQL Server can lock th
es
e r
es
ourc
es
: Item D
es
cription DB A database. File A database file Index An entire index of a table. Table An entire table, including all data and index
es
. Extent A contiguous group of data pag
es
or index pag
es
. Page An 8-KB data page or index page. Key Row lock within an index. Key-range A key-range. Used to lock rang
es
between records in a table to prevent ph
ant
om insertions or deletions into a set of records. Ensur
es
serializable transactions. RID A Row Identifier. Used to individually lock a single row within a table. Application A lock r
es
ource defined by an application. The lock manager knows nothing about the r
es
ource format. It simply compar
es
the 'strings' repr
es
enting the lock r
es
ourc
es
to determine whether it has found a match. If a match is found, it knows that r
es
ource is already locked. Some of the r
es
ourc
es
have “sub-r
es
ourc
es
.” The
following
s are sub-r
es
ourc
es
displayed by the sp_lock output: Database Lock Sub-R
es
ourc
es
: Full Database Lock (default) [BULK-OP-DB] – Bulk Operation Lock for Database [BULK-OP-LOG] – Bulk Operation Lock for Log Table Lock Sub-R
es
ourc
es
: Full Table Lock (default) [UPD-STATS] – Update statistics Lock [COMPILE] – Compile Lock Index Lock sub-R
es
ourc
es
: Full Index Lock (default) [INDEX_ID] – Index ID Lock [INDEX_NAME] – Index Name Lock [BULK_ALLOC] – Bulk Allocation Lock [DEFRAG] – Defragmentation Lock For more information, see also… SOX000821700049 SQL 7.0 How to interpret lock r
es
ource Ids Lock R
es
ource Block The r
es
ource type has the
following
r
es
ource block format: R
es
ource Type (Code) Content DB (2) Data 1: sub-r
es
ource; Data 2: 0; Data 3: 0 File (3) Data 1: File ID; Data 2: 0; Data 3: 0 Index (4) Data 1: Object ID; Data 2: sub-r
es
ource; Data 3: Index ID Table (5) Data 1: Object ID; Data 2: sub-r
es
ource; Data 3: 0. Page (6) Data 1: Page Number; Data 3: 0. Key (7) Data 1: Object ID; Data 2: Index ID; Data 3: Hashed Key Extent (8) Data 1: Extent ID; Data 3: 0. RID (9) Data 1: RID; Data 3: 0. Application (10) Data 1: Application r
es
ource name The rsc_bin column of master..syslockinfo contains the r
es
ource block in hexadecimal format. For an example of how to decode value from this column using the information above, let us assume we have the
following
value: 0x000705001F83D775010002014F0BEC4E With byte swapping within each field, this can be decoded as: Byte 0: Flag – 0x00 Byte 1: R
es
ource Type – 0x07 (Key) Byte 2-3: DBID – 0x0005 Byte 4-7: ObjectID – 0x 75D7831F (1977058079) Byte 8-9: IndexID – 0x0001 Byte 10-16: Hash Key value – 0x 02014F0BEC4E For more information about how to decode this value, see also… Inside SQL Server 2000, pag
es
803 and 806. Key Range Locking Key Range Locking To support SERIALIZABLE transaction sem
ant
ics, SQL Server needs to lock sets of rows specified by a predicate, such as WHERE salary BETWEEN 30000 AND 50000 SQL Server needs to lock data that do
es
not exist! If no rows satisfy the WHERE condition the first time the range is scanned, no rows should be returned on any subsequent scans. Key range locks are similar to row locks on index keys (whether clustered or not). The locks are placed on individual keys rather than at the node level. The hash value consists of all the key components and the locator. So, for a nonclustered index over a heap, where columns c1 and c2 where indexed, the hash would contain contributions from c1, c2 and the RID. A key range lock applied to a particular key means that all keys between the value locked and the next value would be locked for all data modification. Key range locks can lock a slightly larger range than that implied by the WHERE clause. Suppose the
following
select was executed in a transaction with isolation level SERIALIZABLE: SELECT * FROM members WHERE first_name between ‘Al’ and ‘Carl’ If 'Al', 'Bob', and 'Dave' are index keys in the table, the first two of th
es
e would acquire key range locks. Although this would prevent anyone from inserting either 'Alex' or 'Ben', it would also prevent someone from inserting 'Dan', which is not within the range of the WHERE clause. Prior to SQL Server 7.0, page locking was used to prevent ph
ant
oms by locking the entire set of pag
es
on which the ph
ant
om would exist. This can be too conservative. Key Range locking lets SQL Server lock only a much more r
es
trictive area of the table. Impact Key-range locking ensur
es
that th
es
e scenarios are SERIALIZABLE: Range scan query Singleton fetch of nonexistent row Delete operation Insert operation However, the
following
conditions must be satisfied before key-range locking can occur: The transaction-isolation level must be set to SERIALIZABLE. The operation performed on the data must use an index range acc
es
s. Range locking is activated only when query proc
es
sing (such as the optimizer) choos
es
an index path to acc
es
s the data. Key Range Lock Mode Again, the req_mode column of master.dbo.syslockinfo has lock mode code that is one l
es
s than the code valu
es
shown here. Dynamic Locking When modifying individual rows, SQL Server typically would take row locks to maximize concurrency (for example, OLTP, order-entry application). When scanning larger volum
es
of data, it would be more appropriate to take page or table locks to minimize the cost of acquiring locks (for example, DSS, data warehouse, reporting). Locking Decision The decision about which unit to lock is made dynamically, taking many factors into account, including other activity on the system. For example, if there are multiple transactions currently acc
es
sing a table, SQL Server will tend to favor row locking more so than it otherwise would. It may mean the difference between scanning the table now and paying a bit more in locking cost, or having to wait to acquire a more coarse lock. A preliminary locking decision is made during query optimization, but that decision can be adjusted when the query is actually executed. Lock
Es
calation When the lock count for the transaction exceeds and is a multiple of
ES
CALATION_THR
ES
HOLD (1250), the Lock Manager attempts to
es
calate. For example, when a transaction acquired 1250 locks, lock manager will try to
es
calate. The number of locks held may continue to increase after the
es
calation attempt (for example, because new tabl
es
are acc
es
sed, or the previous lock
es
calation attempts failed due to incompatible locks held by another spid). If the lock count for this transaction reach
es
2500 (1250 * 2), Lock Manager will attempt
es
calation again. The Lock Manager looks at the lock memory it is using and if it is more than 40 percent of SQL Server’s allocated buffer pool memory, it tri
es
to find a scan (SD
ES
) where no
es
calation has already been performed. It then repeats the search operation until all scans have been
es
calated or until the memory used drops under the MEMORY_LOAD_
ES
CALATION_THR
ES
HOLD (40%) value. If lock
es
calation is not possible or fails to signific
ant
ly reduce lock memory footprint, SQL Server can continue to acquire locks until the total lock memory reach
es
60 percent of the buffer pool (MAX_LOCK_R
ES
OURCE_MEMORY_PERCENTAGE=60). Lock
es
calation may be also done when a single scan (SD
ES
) holds more than LOCK_
ES
CALATION_THR
ES
HOLD (765) locks. There is no lock
es
calation on temporary tabl
es
or system tabl
es
. Trace Flag 1211 disabl
es
lock
es
calation. Import
ant
Do not relay this to the customer without careful consideration. Lock
es
calation is a nec
es
sary feature, not something to be avoided completely. Trace flags are global and disabling lock
es
calation could lead to out of memory situations, extremely poor performing queri
es
, or other problems. Lock
es
calation tracing can be seen using the Profiler or with the general locking trace flag, -T1200. However, Trace Flag 1200 shows all lock activity so it should not be usable on a production system. For more information, see also… SOX000925700237 “TITLE: SQL 7.0 Lock
es
calation in SQL 7.0” Lock Timeout Application Lock Timeout An application can set lock timeout for a s
es
sion with the SET option: SET LOCK_TIMEOUT N where N is a number of milliseconds. A value of -1 means that there will be no timeout, which is equivalent to the version 6.5 behavior. A value of 0 means that there will be no waiting; if a proc
es
s finds a r
es
ource locked, it will generate error m
es
sage 1222 and continue with the next statement. The current value of LOCK_TIMEOUT is stored in the global variable @@lock_timeout. Note After a lock timeout any transaction containing the statement, is rolled back or canceled by SQL Server 2000 (bug#352640 was filed). This behavior is different from that of SQL Server 7.0. With SQL Server 7.0, the application must have an error handler that can trap error 1222 and if an application do
es
not trap the error, it can proceed unaware that an individual statement within a transaction has been canceled, and errors can occur because statements later in the transaction may depend on the statement that was never executed. Bug#352640 is fixed in hotfix build 8.00.266 whereby a lock timeout will only Internal Lock Timeout At time, internal operations within SQL Server will attempt to acquire locks via lock manager. Typically, th
es
e lock requ
es
ts are issued with “no waiting.” For example, the ghost record proc
es
sing might try to clean up rows on a particular page, and before it can do that, it needs to lock the page. Thus, the ghost record manager will requ
es
t a page lock with no wait so that if it cannot lock the page, it will just move on to other pag
es
; it can always come back to this page later. If you look at SQL Profiler Lock: Timeout events, internal lock timeout typically have a duration value of zero. Lock Duration Lock Mode and Transaction Isolation Level For REPEATABLE READ transaction isolation level, update locks are held until data is read and proc
es
sed, unl
es
s promoted to exclusive locks. "Data is proc
es
sed" means that we have decided whether the row in qu
es
tion matched the search criteria; if not then the update lock is released, otherwise, we get an exclusive lock and make the modification. Consider the
following
query: use northwind go dbcc traceon(3604, 1200, 1211) -- turn on lock tracing -- and disable
es
calation go set transaction isolation level repeatable read begin tran update dbo.[order details] set discount = convert (real, discount) where discount = 0.0 exec sp_lock Update locks are promoted to exclusive locks when there is a match; otherwise, the update lock is released. The sp_lock output verifi
es
that the SPID do
es
not hold any update locks or shared locks at the end of the query. Lock
es
calation is turned off so that exclusive table lock is not held at the end. Warning Do not use trace flag 1200 in a production environment because it produc
es
a lot of output and slows down the server. Trace flag 1211 should not be used unl
es
s you have done extensive study to make sure it helps with performance. Th
es
e trace flags are used here for illustration and learning purpos
es
only. Lock Ownership Most of the locking discussion in this l
es
son relat
es
to locks owned by “transactions.” In addition to transaction, cursor and s
es
sion can be owners of locks and they both affect how long locks are held. For every row that is fetched, when SCROLL_LOCKS option is used, regardl
es
s of the state of a transaction, a cursor lock is held until the next row is fetched or when the cursor is closed. Locks owned by s
es
sion are outside the scope of a transaction. The duration of th
es
e locks are bounded by the connection and the proc
es
s will continue to hold th
es
e locks until the proc
es
s disconnects. A typical lock owned by s
es
sion is the database (DB) lock. Locking – Read Committed Scan Under read committed isolation level, when database pag
es
are scanned, shared locks are held when the page is read and proc
es
sed. The shared locks are released “behind” the scan and allow other transactions to update rows. It is import
ant
to note that the shared lock currently acquired will not be released until shared lock for the next page is succ
es
sfully acquired (this is commonly know as “crabbing”). If the same pag
es
are scanned again, rows may be modified or deleted by other transactions. Locking – Repeatable Read Scan Under repeatable read isolation level, when database pag
es
are scanned, shared locks are held when the page is read and proc
es
sed. SQL Server continu
es
to hold th
es
e shared locks, thus preventing other transactions to update rows. If the same pag
es
are scanned again, previously scanned rows will not change but new rows may be added by other transactions. Locking – Serializable Read Scan Under serializable read isolation level, when database pag
es
are scanned, shared locks are held not only on rows but also on scanned key range. SQL Server continu
es
to hold th
es
e shared locks until the end of transaction. Because key range locks are held, not only will this prevent other transactions from modifying the rows, no new rows can be inserted. Prefetch and Isolation Level Prefetch and Locking Behavior The prefetch feature is available for use with SQL Server 7.0 and SQL Server 2000. When searching for data using a nonclustered index, the index is searched for a particular value. When that value is found, the index points to the disk addr
es
s. The traditional approach would be to immediately issue an I/O for that row, given the disk addr
es
s. The r
es
ult is one synchronous I/O per row and, at most, one disk at a time working to evaluate the query. This do
es
not take adv
ant
age of striped disk sets. The prefetch feature tak
es
a different approach. It continu
es
looking for more record pointers in the nonclustered index. When it has collected a number of them, it provid
es
the storage engine with prefetch hints. Th
es
e hints tell the storage engine that the query proc
es
sor will need th
es
e particular records soon. The storage engine can now issue several I/Os simultaneously, taking adv
ant
age of striped disk sets to execute multiple operations simultaneously. For example, if the engine is scanning a nonclustered index to determine which rows qualify but will eventually need to visit the data page as well to acc
es
s columns that are not in the index, it may decide to submit asynchronous page read requ
es
ts for a group of qualifying rows. The prefetch data pag
es
are then revisited later to avoid waiting for each individual page read to complete in a serial fashion. This data acc
es
s path requir
es
that a lock be held between the prefetch requ
es
t and the row lookup to stabilize the row on the page so it is not to be moved by a page split or clustered key update. For our example, the isolation level of the query is
es
calated to REPEATABLE READ, overriding the transaction isolation level. With SQL Server 7.0 and SQL Server 2000, portions of a transaction can execute at a different transaction isolation level than the entire transaction itself. This is implemented as lock
class
es
. Lock
class
es
are used to control lock lifetime when portions of a transaction need to execute at a stricter isolation level than the underlying transaction. Unfortunately, in SQL Server 7.0 and SQL Server 2000, the lock
class
is created at the topmost operator of the query and hence released only at the end of the query. Currently there is no support to release the lock (lock
class
) after the row has been discarded or fetched by the filter or join operator. This is because isolation level can be set at the query level via a lock
class
, but no lower. Because of this, locks acquired during the query will not be released until the query complet
es
. If prefetch is occurring you may see a single SPID that holds hundreds of Shared KEY or PAG locks even though the connection’s isolation level is READ COMMITTED. Isolation level can be determined from DBCC PSS output. For details about this behavior see “SOX001109700040 INF: Queri
es
with PREFETCH in the plan hold lock until the end of transaction”. Other Locking Mechanism Lock manager do
es
not manage latch
es
and spinlocks. Latch
es
Latch
es
are internal mechanisms used to protect pag
es
while doing operations such as placing a row physically on a page, compr
es
sing space on a page, or retrieving rows from a page. Latch
es
can roughly be divided into I/O latch
es
and non-I/O latch
es
. If you see a high number of non-I/O related latch
es
, SQL Server is usually doing a large number of hash or sort operations in tempdb. You can monitor latch activiti
es
via DBCC SQLPERF(‘WAITSTATS’) command. Spinlock A spinlock is an internal data structure that is used to protect vital information that is shared within SQL Server. On a multi-proc
es
sor machine, when SQL Server tri
es
to acc
es
s a particular r
es
ource protected by a spinlock, it must first acquire the spinlock. If it fails, it execut
es
a loop that will check to see if the lock is available and if not, decrements a counter. If the counter reach
es
zero, it yields the proc
es
sor to another thread and go
es
into a “sleep” (wait) state for a pre-determined amount of time. When it wak
es
, hopefully, the lock is free and available. If not, the loop starts again and it is terminated only when the lock is acquired. The reason for implementing a spinlock is that it is probably l
es
s costly to “spin” for a short time rather than yielding the proc
es
sor. Yielding the proc
es
sor will force an expensive context switch where: The old thread’s state must be saved The new thread’s state must be reloaded The data stored in the L1 and L2 cache are usel
es
s to the proc
es
sor On a single-proc
es
sor computer, the loop is not useful because no other thread can be running and thus, no one can release the spinlock for the currently executing thread to acquire. In this situation, the thread yields the proc
es
sor immediately. L
es
son 2: Concepts – Batch and Transaction This l
es
son outlin
es
some of the common caus
es
that contribute to the perception of a slow server. What You Will Learn After completing this l
es
son, you will be able to: Review batch proc
es
sing and error checking. Review explicit, implicit and autocommit transactions and transaction n
es
ting level. Discuss how commit and rollback transaction done in stored procedure and trigger affects transaction n
es
ting level. Discuss various transaction isolation level and their impact on locking. Discuss the difference between aborting a statement, a transaction, and a batch. D
es
cribe how @@error, @@transcount, and @@rowcount can be used for error checking and handling. Recommended Reading Charter 12 “Transactions and Triggers”, Inside SQL Server 2000 by Kalen Delaney Batch Definition SQL Profiler Statements and Batch
es
To help further your understanding of what is a batch and what is a statement, you can use SQL Profiler to study the definition of batch and statement. Try This: Using SQL Profiler to Analyze Batch 1. Log on to a server with Query Analyzer 2. Startup the SQL Profiler aga
inst
the same server 3. Start a trace using the “StandardSQLProfiler” template 4. Execute the
following
using Query Analyzer: SELECT @@VERSION SELECT @@SPID The ‘SQL:BatchCompleted’ event is captured by the trace. It shows both the statements as a single batch. 5. Now execute the
following
using Query Analyzer {call sp_who()} What shows up? The ‘RPC:Completed’ with the sp_who information. RPC is simply another entry point to the SQL Server to call stored procedur
es
with native data typ
es
. This allows one to avoid parsing. The ‘RPC:Completed’ event should be considered the same as a batch for the purpos
es
of this discussion. Stop the current trace and start a new trace using the “SQLProfilerTSQL_SPs” template. Issue the same command as outlin
es
in step 5 above. Looking at the output, not only can you see the batch markers but each statement as executed within the batch. Autocommit, Explicit, and Implicit Transaction Autocommit Transaction Mode (Default) Autocommit mode is the default transaction management mode of SQL Server. Every Transact-SQL statement, whether it is a standalone statement or part of a batch, is committed or rolled back when it complet
es
. If a statement complet
es
succ
es
sfully, it is committed; if it encounters any error, it is rolled back. A SQL Server connection operat
es
in autocommit mode whenever this default mode has not been overridden by either explicit or implicit transactions. Autocommit mode is also the default mode for ADO, OLE DB, ODBC, and DB-Library. A SQL Server connection operat
es
in autocommit mode until a BEGIN TRANSACTION statement starts an explicit transaction, or implicit transaction mode is set on. When the explicit transaction is committed or rolled back, or when implicit transaction mode is turned off, SQL Server returns to autocommit mode. Explicit Transaction Mode An explicit transaction is a transaction that starts with a BEGIN TRANSACTION statement. An explicit transaction can contain one or more statements and must be terminated by either a COMMIT TRANSACTION or a ROLLBACK TRANSACTION statement. Implicit Transaction Mode SQL Server can automatically or, more precisely, implicitly start a transaction for you if a SET IMPLICIT_TRANSACTIONS ON statement is run or if the implicit transaction option is turned on globally by running sp_configure ‘user options’ 2. (Actually, the bit mask 0x2 must be turned on for the user option so you might have to perform an ‘OR’ operation with the existing user option value.) See SQL Server 2000 Books Online on how to turn on implicit transaction under ODBC and OLE DB (acdata.chm::/ac_8_md_06_2g6r.htm). Transaction N
es
ting Explicit transactions can be n
es
ted. Committing inner transactions is ignored by SQL Server other than to decrements @@TRANCOUNT. The transaction is either committed or rolled back based on the action taken at the end of the outermost transaction. If the outer transaction is committed, the inner n
es
ted transactions are also committed. If the outer transaction is rolled back, then all inner transactions are also rolled back, regardl
es
s of whether the inner transactions were individually committed. Each call to COMMIT TRANSACTION appli
es
to the last executed BEGIN TRANSACTION. If the BEGIN TRANSACTION statements are n
es
ted, then a COMMIT statement appli
es
only to the last n
es
ted transaction, which is the innermost transaction. Even if a COMMIT TRANSACTION transaction_name statement within a n
es
ted transaction refers to the transaction name of the outer transaction, the commit appli
es
only to the innermost transaction. If a ROLLBACK TRANSACTION statement without a transaction_name parameter is executed at any level of a set of n
es
ted transaction, it rolls back all the n
es
ted transactions, including the outermost transaction. The @@TRANCOUNT function records the current transaction n
es
ting level. Each BEGIN TRANSACTION statement increments @@TRANCOUNT by one. Each COMMIT TRANSACTION statement decrements @@TRANCOUNT by one. A ROLLBACK TRANSACTION statement that do
es
not have a transaction name rolls back all n
es
ted transactions and decrements @@TRANCOUNT to 0. A ROLLBACK TRANSACTION that us
es
the transaction name of the outermost transaction in a set of n
es
ted transactions rolls back all the n
es
ted transactions and decrements @@TRANCOUNT to 0. When you are unsure if you are already in a transaction, SELECT @@TRANCOUNT to determine whether it is 1 or more. If @@TRANCOUNT is 0 you are not in a transaction. You can also find the transaction n
es
ting level by checking the sysproc
es
s.open_tran column. See SQL Server 2000 Books Online topic “N
es
ting Transactions” (acdata.chm::/ac_8_md_06_66nq.htm) for more information. Statement, Transaction, and Batch Abort One batch can have many statements and one transaction can have multiple statements, also. One transaction can span multiple batch
es
and one batch can have multiple transactions. Statement Abort Currently executing statement is aborted. This can be a bit confusing when you start talking about statements in a trigger or stored procedure. Let us look closely at the
following
trigger: CREATE TRIGGER TRG8134 ON TBL8134 AFTER INSERT AS BEGIN SELECT 1/0 SELECT 'Next command in trigger' END To fire the INSERT trigger, the batch could be as simple as ‘INSERT INTO TBL8134 VALU
ES
(1)’. However, the trigger contains two statements that must be executed as part of the batch to satisfy the clients insert requ
es
t. When the ‘SELECT 1/0’ caus
es
the divide by zero error, a statement abort is issued for the ‘SELECT 1/0’ statement. Batch and Transaction Abort On SQL Server 2000 (and SQL Server 7.0) whenever a non-informational error is encountered in a trigger, the statement abort is promoted to a batch and transactional abort. Thus, in the example the statement abort for ‘select 1/0’ promotion r
es
ults in an entire batch abort. No further statements in the trigger or batch will be executed and a rollback is issued. On SQL Server 6.5, the statement aborts immediately and r
es
ults in a transaction abort. However, the r
es
t of the statements within the trigger are executed. This trigger could return ‘Next command in trigger’ as a r
es
ult set. Once the trigger complet
es
the batch abort promotion tak
es
effect. Conversely, submitting a similar set of statements in a standalone batch can r
es
ult in different behavior. SELECT 1/0 SELECT 'Next command in batch' Not considering the set option possibiliti
es
, a divide by zero error generally r
es
ults in a statement abort. Since it is not in a trigger, the promotion to a batch abort is avoided and subsequent SELECT statement can execute. The programmer should add an “if @@ERROR” check immediately after the ‘select 1/0’ to T-SQL execution to control the flow correctly. Aborting and Set Options ARITHABORT If SET ARITHABORT is ON, th
es
e error conditions cause the query or batch to terminate. If the errors occur in a transaction, the transaction is rolled back. If SET ARITHABORT is OFF and one of th
es
e errors occurs, a warning m
es
sage is displayed, and NULL is assigned to the r
es
ult of the arithmetic operation. When an INSERT, DELETE, or UPDATE statement encounters an arithmetic error (overflow, divide-by-zero, or a domain error) during expr
es
sion evaluation when SET ARITHABORT is OFF, SQL Server inserts or updat
es
a NULL value. If the target column is not nullable, the insert or update action fails and the user receiv
es
an error. XACT_ABORT When SET XACT_ABORT is ON, if a Transact-SQL statement rais
es
a run-time error, the entire transaction is terminated and rolled back. When OFF, only the Transact-SQL statement that raised the error is rolled back and the transaction continu
es
proc
es
sing. Compile errors, such as syntax errors, are not affected by SET XACT_ABORT. For example: CREATE TABLE t1 (a int PRIMARY KEY) CREATE TABLE t2 (a int REFERENC
ES
t1(a)) GO INSERT INTO t1 VALU
ES
(1) INSERT INTO t1 VALU
ES
(3) INSERT INTO t1 VALU
ES
(4) INSERT INTO t1 VALU
ES
(6) GO SET XACT_ABORT OFF GO BEGIN TRAN INSERT INTO t2 VALU
ES
(1) INSERT INTO t2 VALU
ES
(2) /* Foreign key error */ INSERT INTO t2 VALU
ES
(3) COMMIT TRAN SELECT 'Continue running batch 1...' GO SET XACT_ABORT ON GO BEGIN TRAN INSERT INTO t2 VALU
ES
(4) INSERT INTO t2 VALU
ES
(5) /* Foreign key error */ INSERT INTO t2 VALU
ES
(6) COMMIT TRAN SELECT 'Continue running batch 2...' GO /* Select shows only keys 1 and 3 added. Key 2 insert failed and was rolled back, but XACT_ABORT was OFF and r
es
t of transaction succeeded. Key 5 insert error with XACT_ABORT ON caused all of the second transaction to roll back. Also note that 'Continue running batch 2...' is not Returned to indicate that the batch is aborted. */ SELECT * FROM t2 GO DROP TABLE t2 DROP TABLE t1 GO Compile and Run-time Errors Compile Errors Compile errors are encountered during syntax checks, security checks, and other general operations to prepare the batch for execution. Th
es
e errors can prevent the optimization of the query and thus lead to immediate abort. The statement is not run and the batch is aborted. The transaction state is generally left untouched. For example, assume there are four statements in a particular batch. If the third statement has a syntax error, none of the statements in the batch is executed. Optimization Errors Optimization errors would include rare situations where the statement encounters a problem when attempting to build an optimal execution plan. Example: “too many tabl
es
referenced in the query” error is reported because a “work table” was added to the plan. Runtime Errors Runtime errors are those that are encountered during the execution of the query. Consider the
following
batch: SELECT * FROM pubs.dbo.titl
es
UPDATE pubs.dbo.authors SET au_lname = au_lname SELECT * FROM foo UPDATE pubs.dbo.authors SET au_lname = au_lname If you run the above statements in a batch, the first two statements will be executed, the third statement will fail because table foo do
es
not exist, and the batch will terminate. Deferred Name R
es
olution is the feature that allows this batch to start executing before r
es
olving the object foo. This feature allows SQL Server to delay object r
es
olution and place a “placeholder” in the query’s execution. The object referenced by the placeholder is r
es
olved until the query is executed. In our example, the execution of the statement “SELECT * FROM foo” will trigger another compile proc
es
s to r
es
olve the name again. This time, error m
es
sage 208 is returned. Error: 208, Level 16, State 1, Line 1 Invalid object name 'foo'. M
es
sage 208 can be encountered as a runtime or compile error depending on whether the Deferred Name R
es
olution feature is available. In SQL Server 6.5 this would be considered a compile error and on SQL Server 2000 (and SQL Server7.0) as a runtime error due to Deferred Name R
es
olution. In the
following
example, if a trigger referenced authors2, the error is detected as SQL Server attempts to execute the trigger. However, under SQL Server 6.5 the create trigger statement fails because authors2 do
es
not exist at compile time. When errors are encountered in a trigger, generally, the statement, batch, and transaction are aborted. You should be able to observe this by running the
following
script in pubs database: Create table tblT
es
t(iID int) go create trigger trgInsert on tblT
es
t for INSERT as begin select * from authors select * from authors2 select * from titl
es
end go begin tran select 'Before' insert into tblT
es
t valu
es
(1) select 'After' go select @@TRANCOUNT go When run in a batch, the statement and the batch are aborted but the transaction remains active. The follow script illustrat
es
this: begin tran select 'Before' select * from authors2 select 'After' go select @@TRANCOUNT go One other factor in a compile versus runtime error is implicit data type conversions. If you were to run the
following
statements on SQL Server 6.5 and SQL Server 2000 (and SQL Server 7.0): create table tblData(dtData datetime) go select 1 insert into tblData valu
es
(12/13/99) go On SQL Server 6.5, you get an error before execution of the batch begins so no statements are executed and the batch is aborted. Error: 206, Level 16, State 2, Line 2 Operand type clash: int is incompatible with datetime On SQL Server 2000, you get the default value (1900-01-01 00:00:00.000) inserted into the table. SQL Server 2000 implicit data type conversion treats this as integer division. The integer division of 12/13/99 is 0, so the default date and time value is inserted, no error returned. To correct the problem on either version is to wrap the date string with quot
es
. See Bug #56118 (sqlbug_70) for more details about this situation. Another example of a runtime error is a 605 m
es
sage. Error: 605 Attempt to fetch logical page %S_PGID in database '%.*ls' belongs to object '%.*ls', not to object '%.*ls'. A 605 error is always a runtime error. However, depending on the transaction isolation level, (e.g. using the NOLOCK lock hint),
es
tablished by the SPID the handling of the error can vary. Specifically, a 605 error is considered an ACC
ES
S error. Errors assoc
iated
with buffer and page acc
es
s are found in the 600 seri
es
of errors. When the error is encountered, the isolation level of the SPID is examined to determine proper handling based on information or fatal error level. Transaction Error Checking Not all errors cause transactions to automatically rollback. Although it is difficult to determine exactly which errors will rollback transactions and which errors will not, the main idea here is that programmers must perform error checking and handle errors appropriately. Error Handling Raiserror Details Raiserror seems to be a source of confusion but is really rather simple. Raiserror with severity levels of 20 or higher will terminate the connection. Of course, when the connection is terminated a full rollback of any open transaction will immediately be
inst
ant
iated
by the SQL Server (except distributed transaction with DTC involved). Severity levels lower than 20 will simply r
es
ult in the error m
es
sage being returned to the client. They do not affect the transaction scope of the connection. Consider the
following
batch: use pubs begin tran update authors set au_lname = 'smith' raiserror ('This is bad', 19, 1) with log select @@trancount With severity set at 19, the 'select @@trancount' will be executed after the raiserror statement and will return a value of 1. If severity is changed to 20, then the select statement will not run and the connection is broken. Import
ant
Error handling must occur not only in T-SQL batch
es
and stored procedur
es
, but also in application program code. Transactions and Triggers (1 of 2) Basic behavior assum
es
the implicit transactions setting is set to OFF. This behavior mak
es
it possible to identify busin
es
s logic errors in a trigger, raise an error, rollback the action, and add an audit table entry. Logically, the insert to the audit table cannot take place before the ROLLBACK action and you would not w
ant
to build in the audit table insert into every applications error handler that violated the busin
es
s rule of the trigger. For more information, see also… SQL Server 2000 Books Online topic “Rollbacks in stored procedure and triggers“ (acdata.chm::/ac_8_md_06_4qcz.htm) IMPLICIT_TRANSACTIONS ON Behavior The behavior of firing other triggers on the same table can be tricky. Say you added a trigger that checks the CODE field. Read only versions of the rows contain the code ‘RO’ and read/write versions use ‘RW.’ Whenever someone tri
es
to delete a row with a code ‘RO’ the trigger issu
es
the rollback and logs an audit table entry. However, you also have a second trigger that is r
es
ponsible for cascading delete operations. One client could issue the delete without implicit transactions on and only the current trigger would execute and then terminate the batch. However, a second client with implicit transactions on could issue the same delete and the secondary trigger would fire. You end up with a situation in which the cascading delete operations can take place (are committed) but the initial row remains in the table because of the rollback operation. None of the delete operations should be allowed but because the transaction scope was r
es
tarted because of the implicit transactions setting, they did. Transactions and Triggers (2 of 2) It is extremely difficult to determine the execution state of a trigger when using explicit rollback statements in combination with implicit transactions. The RETURN statement is not allowed to return a value. The only way I have found to set the @@ERROR is using a ‘raiserror’ as the last execution statement in the last trigger to execute. If you modify the example, this
following
RAISERROR statement will set @@ERROR to 50000: CREATE TRIGGER trgT
es
t on tblT
es
t for INSERT AS BEGIN ROLLBACK INSERT INTO tblAudit VALU
ES
(1) RAISERROR('This is bad', 14,1) END However, this value do
es
not carry over to a secondary trigger for the same table. If you raise an error at the end of the first trigger and then look at @@ERROR in the secondary trigger the @@ERROR remains 0. Carrying Forward an Active/Open Transaction It is possible to exit from a trigger and carry forward an open transaction by issuing a BEGIN TRAN or by setting implicit transaction on and doing INSERT, UPDATE, or DELETE. Warning It is never recommended that a trigger call BEGIN TRANSACTION. By doing this you increment the transaction count. Invalid code logic, not calling commit transaction, can lead to a situation where the transaction count remains elevated upon exit of the trigger. Transaction Count The behavior is better explained by understanding how the server works. It do
es
not matter whether you are in a transaction, when a modification tak
es
place the transaction count is incremented. So, in the simpl
es
t form, during the proc
es
sing of an insert the transaction count is 1. On completion of the insert, the server will commit (and thus decrement the transaction count). If the commit identifi
es
the transaction count has returned to 0, the actual commit proc
es
sing is completed. Issuing a commit when the transaction count is greater than 1 simply decrements the n
es
ted transaction counter. Thus, when we enter a trigger, the transaction count is 1. At the completion of the trigger, the transaction count will be 0 due to the commit issued at the end of the modification statement (insert). In our example, if the connection was already in a transaction and called the second INSERT, since implicit transaction is ON, the transaction count in the trigger will be 2 as long as the ROLLBACK is not executed. At the end of the insert, the commit is again issued to decrement the transaction reference count to 1. However, the value do
es
not return to 0 so the transaction remains open/active. Subsequent triggers are only fired if the transaction count at the end of the trigger remains greater than or equal to 1. The key to continuation of secondary triggers and the batch is the transaction count at the end of a trigger execution. If the trigger that performs a rollback has done an explicit begin transaction or us
es
implicit transactions, subsequent triggers and the batch will continue. If the transaction count is not 1 or greater, subsequent triggers and the batch will not execute. Warning Forcing the transaction count after issuing a rollback is dangerous because you can easily loose track of your transaction n
es
ting level. When performing an explicit rollback in a trigger, you should immediately issue a return statement to maintain consistent behavior between a connection with and without implicit transaction settings. This will force the trigger(s) and batch to terminate immediately. One of the methods of dealing with this issue is to run ‘SET IMPLICIT_TRANSACTIONS OFF’ as the first statement of any trigger. Other methods may entails checking @@TRANCOUNT at the end of the trigger and continue to COMMIT the transaction as long as @@TRANCOUNT is greater than 1. Exampl
es
The
following
exampl
es
are based on this table: create table tbl50000Insert (iID int NOT NULL) go Note If more than one trigger is used, to guar
ant
ee the trigger firing sequence, the sp_settriggerorder command should be used. This command is omitted in th
es
e exampl
es
to simplify the complexity of the statements. First Example In the first example, the second trigger was never fired and the batch, starting with the insert statement, was aborted. Thus, the print statement was never issued. print('Trigger issu
es
rollback - cancels batch') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback tran select 'End of trigger', @@TRANCOUNT as 'TRANCOUNT' end go create trigger trg50000Insert2 on tbl50000Insert for INSERT as begin select 'In Trigger2' select 'Trigger 2 Inserted', * from inserted end go insert into tbl50000Insert valu
es
(1) print('---------------------- In same batch') select * from tbl50000Insert go -- Cleanup drop trigger trg50000Insert drop trigger trg50000Insert2 go delete from tbl50000Insert Second Example The next example shows that since a new transaction is started, the second trigger will be fired and the print statement in the batch will be executed. Note that the insert is rolled back. print('Trigger issu
es
rollback - increas
es
tran count to continue batch') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback tran begin tran end go create trigger trg50000Insert2 on tbl50000Insert for INSERT as begin select 'In Trigger2' select 'Trigger 2 Inserted', * from inserted end go insert into tbl50000Insert valu
es
(2) print('---------------------- In same batch') select * from tbl50000Insert go -- Cleanup drop trigger trg50000Insert drop trigger trg50000Insert2 go delete from tbl50000Insert Third Example In the third example, the raiserror statement is used to set the @@ERROR value and the BEGIN TRAN statement is used in the trigger to allow the batch to continue to run. print('Trigger issu
es
rollback - us
es
raiserror to set @@ERROR') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback tran begin tran -- Increase @@trancount to allow -- batch to continue select @@trancount as ‘Trancount’ raiserror('This is from the trigger', 14,1) end go insert into tbl50000Insert valu
es
(3) select @@ERROR as 'ERROR', @@TRANCOUNT as 'Trancount' go -- Cleanup drop trigger trg50000Insert go delete from tbl50000Insert Fourth Example For the fourth example, a second trigger is added to illustrate the fact that @@ERROR value set in the first trigger will not be seen in the second trigger nor will it show up in the batch after the second trigger is fired. print('Trigger issu
es
rollback - us
es
raiserror to set @@ERROR, not seen in second trigger and cleared in batch') go create trigger trg50000Insert on tbl50000Insert for INSERT as begin select 'Inserted', * from inserted rollback begin tran -- Increase @@trancount to -- allow batch to continue select @@TRANCOUNT as 'Trancount' raiserror('This is from the trigger', 14,1) end go create trigger trg50000Insert2 on tbl50000Insert for INSERT as begin select @@ERROR as 'ERROR', @@TRANCOUNT as 'Trancount' end go insert into tbl50000Insert valu
es
(4) select @@ERROR as 'ERROR', @@TRANCOUNT as 'Trancount' go -- Cleanup drop trigger trg50000Insert drop trigger trg50000Insert2 go delete from tbl50000Insert L
es
son 3: Concepts – Locks and Applications This l
es
son outlin
es
some of the common caus
es
that contribute to the perception of a slow server. What You Will Learn After completing this l
es
son, you will be able to: Explain how lock hints are used and their impact. Discuss the effect on locking when an application us
es
Microsoft Transaction Server. Identify the different kinds of deadlocks including distributed deadlock. Recommended Reading Charter 14 “Locking”, Inside SQL Server 2000 by Kalen Delaney Charter 16 “Query Tuning”, Inside SQL Server 2000 by Kalen Delaney Q239753 – Deadlock Situation Not Detected by SQL Server Q288752 – Blocked SPID Not Participating in Deadlock May Incorrectly be Chosen as victim Locking Hints UPDLOCK If update locks are used
inst
ead of shared locks while reading a table, the locks are held until the end of the statement or transaction. UPDLOCK has the adv
ant
age of allowing you to read data (without blocking other readers) and update it later with the assurance that the data has not changed since you last read it. READPAST READPAST is an optimizer hint for use with SELECT statements. When this hint is used, SQL Server will read past locked rows. For example, assume table T1 contains a single integer column with the valu
es
of 1, 2, 3, 4, and 5. If transaction A chang
es
the value of 3 to 8 but has not yet committed, a SELECT * FROM T1 (READPAST) yields valu
es
1, 2, 4, 5. Tip READPAST only appli
es
to transactions operating at READ COMMITTED isolation and only reads past row-level locks. This lock hint can be used to implement a work queue on a SQL Server table. For example, assume there are many external work requ
es
ts being thrown into a table and they should be serviced in approximate insertion order but they do not have to be completely FIFO. If you have 4 worker threads consuming work items from the queue they could each pick up a record using read past locking and then delete the entry from the queue and commit when they're done. If they fail, they could rollback, leaving the entry on the queue for the next worker thread to pick up. Caution The READPAST hint is not compatible with HOLDLOCK. Try This: Using Locking Hints 1. Open a Query Window and connect to the pubs database. 2. Execute the
following
statements (--Conn 1 is optional to help you keep track of each connection): BEGIN TRANSACTION -- Conn 1 UPDATE titl
es
SET price = price * 0.9 WHERE title_id = 'BU1032' 3. Open a second connection and execute the
following
statements: SELECT @@lock_timeout -- Conn 2 GO SELECT * FROM titl
es
SELECT * FROM authors 4. Open a third connection and execute the
following
statements: SET LOCK_TIMEOUT 0 -- Conn 3 SELECT * FROM titl
es
SELECT * FROM authors 5. Open a fourth connection and execute the
following
statement: SELECT * FROM titl
es
(READPAST) -- Conn 4 WHERE title_ID < 'C' SELECT * FROM authors How many records were returned? 3 6. Open a fifth connection and execute the
following
statement: SELECT * FROM titl
es
(NOLOCK) -- Conn 5 WHERE title_ID 0 the lock manager also checks for deadlocks every time a SPID gets blocked. So a single deadlock will trigger 20 seconds of more immediate deadlock detection, but if no additional deadlocks occur in that 20 seconds, the lock manager no longer checks for deadlocks at each block and detection again only happens every 5 seconds. Although normally not needed, you may use trace flag -T1205 to trace the deadlock detection proc
es
s. Note Please note the distinction between application lock and other locks’ deadlock detection. For application lock, we do not rollback the transaction of the deadlock victim but simply return a -3 to sp_getapplock, which the application needs to handle itself. Deadlock R
es
olution How is a deadlock r
es
olved? SQL Server picks one of the connections as a deadlock victim. The victim is chosen based on either which is the least expensive transaction (calculated using the number and size of the log records) to roll back or in which proc
es
s “SET DEADLOCK_PRIORITY LOW” is specified. The victim’s transaction is rolled back, held locks are released, and SQL Server sends error 1205 to the victim’s client application to notify it that it was chosen as a victim. The other proc
es
s can then obtain acc
es
s to the r
es
ource it was waiting on and continue. Error 1205: Your transaction (proc
es
s ID #%d) was deadlocked with another proc
es
s and has been chosen as the deadlock victim. Rerun your transaction. Symptoms of deadlocking Error 1205 usually is not written to the SQL Server errorlog. Unfortunately, you cannot use sp_alterm
es
sage to cause 1205 to be written to the errorlog. If the client application do
es
not capture and display error 1205, some of the symptoms of deadlock occurring are: Clients complain of mysteriously canceled queri
es
when using certain featur
es
of an application. May be accompanied by exc
es
sive blocking. Lock contention increas
es
the chanc
es
that a deadlock will occur. Triggers and Deadlock Triggers promote the deadlock priority of the SPID for the life of the trigger execution when the DEADLOCK PRIORITY is not set to low. When a statement in a trigger caus
es
a deadlock to occur, the SPID executing the trigger is given preferential treatment and will not become the victim. Warning Bug 235794 is filed aga
inst
SQL Server 2000 where a blocked SPID that is not a particip
ant
of a deadlock may incorrectly be chosen as a deadlock victim if the SPID is blocked by one of the deadlock particip
ant
s and the SPID has the least amount of transaction logging. See KB article Q288752: “Blocked Spid Not Participating in Deadlock May Incorrectly be Chosen as victim” for more information. Distributed Deadlock – Scenario 1 Distributed Deadlocks The term distributed deadlock is ambiguous. There are many typ
es
of distributed deadlocks. Scenario 1 Client application opens connection A, begins a transaction, acquir
es
some locks, opens connection B, connection B gets blocked by A but the application is d
es
igned to not commit A’s transaction until B complet
es
. Note SQL Server has no way of knowing that connection A is somehow dependent on B – they are two distinct connections with two distinct transactions. This situation is discussed in scenario #4 in “Q224453 INF: Understanding and R
es
olving SQL Server 7.0 Blocking Problems”. Distributed Deadlock – Scenario 2 Scenario 2 Distributed deadlock involving bound connections. Two connections can be bound into a single transaction context with sp_getbindtoken/sp_binds
es
sion or via DTC. Spid 60 enlists in a transaction with spid 61. A third spid 62 is blocked by spid 60, but spid 61 is blocked by spid 62. Because they are doing work in the same transaction, spid 60 cannot commit until spid 61 finish
es
his work, but spid 61 is blocked by 62 who is blocked by 60. This scenario is d
es
cribed in article “Q239753 - Deadlock Situation Not Detected by SQL Server.” Note SQL Server 6.5 and 7.0 do not detect this deadlock. The SQL Server 2000 deadlock detection algorithm has been enhanced to detect this type of distributed deadlock. The diagram in the slide illustrat
es
this situation. R
es
ourc
es
locked by a spid are below that spid (in a box). Arrows indicate blocking and are drawn from the blocked spid to the r
es
ource that the spid requir
es
. A circle repr
es
ents a transaction; spids in the same transaction are shown in the same circle. Distributed Deadlock – Scenario 3 Scenario 3 Distributed deadlock involving linked servers or server-to-server RPC. Spid 60 on Server 1 execut
es
a stored procedure on Server 2 via linked server. This stored procedure do
es
a loopback linked server query aga
inst
a table on Server 1, and this connection is blocked by a lock held by Spid 60. Note No version of SQL Server is currently d
es
igned to detect this distributed deadlock. L
es
son 4: Information Collection and Analysis This l
es
son outlin
es
some of the common caus
es
that contribute to the perception of a slow server. What You Will Learn After completing this l
es
son, you will be able to: Identify specific information needed for troubl
es
hooting issu
es
. Locate and collect information needed for troubl
es
hooting issu
es
. Analyze output of DBCC Inputbuffer, DBCC PSS, and DBCC Page commands. Review information collected from master.dbo.sysproc
es
s
es
table. Review information collected from master.dbo.syslockinfo table. Review output of sp_who, sp_who2, sp_lock. Analyze Profiler log for query usage pattern. Review output of trace flags to help troubl
es
hoot deadlocks. Recommended Reading Q244455 - INF: Definition of Sysproc
es
s
es
Waittype and Lastwaittype Fields Q244456 - INF: D
es
cription of DBCC PSS Command for SQL Server 7.0 Q271509 - INF: How to Monitor SQL Server 2000 Blocking Q251004 - How to Monitor SQL Server 7.0 Blocking Q224453 - Understanding and R
es
olving SQL Server 7.0 Blocking Problem Q282749 – BUG: Deadlock information reported with SQL Server 2000 Profiler Locking and Blocking Try This: Examine Blocked Proc
es
s
es
1. Open a Query Window and connect to the pubs database. Execute the
following
statements: BEGIN TRAN -- connection 1 UPDATE titl
es
SET price = price + 1 2. Open another connection and execute the
following
statement: SELECT * FROM titl
es
-- connection 2 3. Open a third connection and execute sp_who; note the proc
es
s id (spid) of the blocked proc
es
s. (Connection 3) 4. In the same connection, execute the
following
: SELECT spid, cmd, waittype FROM master..sysproc
es
s
es
WHERE waittype 0 -- connection 3 5. Do not close any of the connections! What was the wait type of the blocked proc
es
s? Try This: Look at locks held Assum
es
all your connections are still open from the previous exercise. • Execute sp_lock -- Connection 3 What locks is the proc
es
s from the previous example holding? Make sure you run ROLLBACK TRAN in Connection 1 to clean up your transaction. Collecting Information See Module 2 for more about how to gather this information using various tools. Recognizing Blocking Problems How to Recognize Blocking Problems Users complain about poor performance at a certain time of day, or after a certain number of users connect. SELECT * FROM sysproc
es
s
es
or sp_who2 shows non-zero valu
es
in the blocked or BlkBy column. More severe blocking incidents will have long blocking chains or large sysproc
es
s
es
.waittime valu
es
for blocked spids. Possibl
C# Game Programming Cookbook for Unity 3D - 2014
Acknowledgments xiii Introduction xv 1. Making Gam
es
the Modular Way 1 1.1 Import
ant
Programming Concepts.....................................2 1.1.1 Manager and Controller Scripts...............................2 1.1.2 Script Communication.......................................3 1.1.3 Using the Singleton Pattern in Unity...........................5 1.1.4 Inheritance.................................................6 1.1.5 Where to Now?.............................................8 2. Building the Core Game Framework 9 2.1 Controllers and Managers............................................11 2.1.1 Controllers................................................11 2.1.2 Managers.................................................11 2.2 Building the Core Framework Scripts..................................11 2.2.1 BaseGameController.cs.....................................12 2.2.1.1 Script Breakdown................................14 viii Contents 2.2.2 Scene Manager.............................................17 2.2.2.1 Script Breakdown................................17 2.2.3 ExtendedCustomMonoBehavior.cs...........................19 2.2.4 BaseUserManager.cs........................................20 2.2.4.1 Script Breakdown................................22 2.2.5 BasePlayerManager.cs.......................................22 2.2.5.1 Script Breakdown................................23 2.2.6 BaseInputController.cs......................................24 2.2.6.1 Script Breakdown................................26 3. Player Structure 29 3.1 Game-Specific Player Controller......................................31 3.2 Dealing with Input..................................................32 3.3 Player Manager.....................................................35 3.3.1 Script Breakdown..........................................36 3.4 User Data Manager (Dealing with Player Stats Such as Health, Liv
es
, etc.)....37 3.4.1 Script Breakdown..........................................39 4. Recip
es
: Common Components 41 4.1 Introduction.......................................................41 4.2 The Timer
Class
....................................................43 4.2.1 Script Breakdown..........................................45 4.3 Spawn Scripts......................................................48 4.3.1 A Simple Spawn Controller..................................49 4.3.1.1 Script Breakdown................................52 4.3.2 Trigger Spawner...........................................56 4.3.3 Path Spawner..............................................57 4.3.3.1 Script Breakdown................................61 4.4 Set Gravity.........................................................66 4.5 Pretend Friction—Friction Simulation to Prevent Slipping Around........66 4.5.1 Script Breakdown..........................................68 4.6 Cameras. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68 4.6.1 Third-Person Camera.......................................69 4.6.1.1 Script Breakdown................................71 4.6.2 Top-Down Camera.........................................74 4.6.2.1 Script Breakdown................................74 4.7 Input Scripts.......................................................75 4.7.1 Mouse Input...............................................75 4.7.1.1 Script Breakdown................................76 4.7.2 Single Axis Keyboard Input.................................78 4.8 Automatic Self-D
es
truction Script.....................................79 4.8.1 Script Breakdown..........................................79 4.9 Automatic Object Spinner............................................79 4.9.1 Script Breakdown..........................................80 ix Contents 4.10 Scene Manager.....................................................81 4.10.1 Script Breakdown..........................................82 5. Building Player Movement Controllers 85 5.1 Shoot ’Em Up Spac
es
hip.............................................85 5.2 Humanoid Character................................................91 5.2.1 Script Breakdown..........................................96 5.3 Wheeled Vehicle...................................................106 5.3.1 Script Breakdown.........................................109 5.3.2 Wheel Alignment.........................................114 5.3.3 Script Breakdown.........................................116 6. Weapon Systems 121 6.1 Building the Scripts................................................122 6.1.1 BaseWeaponController.cs..................................122 6.1.1.1 Script Breakdown...............................127 6.1.2 BaseWeaponScript.cs......................................134 6.1.2.1 Script Breakdown...............................138 7. Recipe: Waypoints Manager 143 7.1 Waypoint System..................................................143 8. Recipe: Sound Manager 157 8.1 The Sound Controller...............................................158 8.1.1 Script Breakdown.........................................160 8.2 The Music Player...................................................163 8.2.1 Script Breakdown.........................................165 8.3 Adding Sound to the Weapons.......................................167 9. AI Manager 169 9.1 The AI State Control Script..........................................171 9.2 The Base AI Control Script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .172 9.2.1 Script Breakdown.........................................185 9.3 Adding Weapon Control to the AI Controller..........................206 9.3.1 Script Breakdown.........................................210 10. Menus and User Interface 215 10.1 The Main Menu....................................................215 10.1.1 Script Breakdown.........................................223 10.2 In-Game User Interface.............................................231 x Contents 11. Dish: Lazer Blast Survival 233 11.1 Main Menu Scene..................................................235 11.2 Main Game Scene..................................................236 11.3 Prefabs...........................................................237 11.4 Ingredients........................................................238 11.5 Game Controller...................................................239 11.5.1 Script Breakdown.........................................243 11.6 Player Controller...................................................250 11.6.1 Script Breakdown.........................................253 11.7 Enemi
es
..........................................................259 11.7.1 Script Breakdown.........................................260 11.8 Wave Spawning and Control........................................261 11.8.1 Script Breakdown.........................................263 11.9 Wave Properti
es
...................................................265 11.10 Weapons and Projectil
es
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..266 11.11 User Interface.....................................................266 11.11.1 Script Breakdown.........................................267 12. Dish: Metal Vehicle Doom 271 12.1 Main Menu Scene..................................................272 12.2 Main Game Scene..................................................272 12.2.1 Prefabs...................................................275 12.3 Ingredients........................................................275 12.3.1 Game Controller..........................................276 12.3.1.1 Script Breakdown...............................282 12.3.2 Race Controller...........................................291 12.3.2.1 Script Breakdown...............................297 12.3.3 Global Race Manager......................................306 12.3.3.1 Script Breakdown...............................311 12.3.4 Vehicle/Custom Player Control.............................318 12.3.4.1 Script Breakdown...............................327 12.3.5 User Interface.............................................344 13. Dish: Making the Game Tank Battle 345 13.1 Main Game Scene..................................................347 13.2 Prefabs...........................................................349 13.3 Ingredients........................................................349 13.4 Game Controller...................................................350 13.4.1 Script Breakdown.........................................356 13.5 Battle Controller...................................................361 13.5.1 Script Breakdown.........................................363 13.6 Global Battle Manager..............................................364 13.6.1 Script Breakdown.........................................368 13.7 Players............................................................373 13.7.1 Script Breakdown.........................................382 xi Contents 13.8 AI Chasing with SetAIChaseTargetBasedOnTag.cs.....................383 13.8.1 Script Breakdown.........................................385 14. Dish: Making the Game Interstellar Paranoids 389 14.1 Main Menu.......................................................392 14.2 Game Scen
es
......................................................392 14.3 Prefabs...........................................................393 14.3.1 Ingredients...............................................394 14.3.2 Game Controller..........................................395 14.3.2.1 Script Breakdown...............................401 14.3.3 Player Spac
es
hip..........................................411 14.3.3.1 Script Breakdown...............................415 14.3.4 Enemi
es
..................................................423 14.3.4.1 Script Breakdown...............................424 14.3.5 Waypoint Follower........................................426 14.3.5.1 Script Breakdown...............................427 Final Note 429 xiii I would like to thank my wife for all the encouragement, support, and nice cups of tea. I would also like to thank my mum and dad, my brother Steve, and everyone else who knows me. Sophie cat, be nice to the boys. Sincere thanks go to the many people who positively influence my life directly or indirectly: Michelle Ashton, Brian Robbins, George Bray, Nadeem Rasool, Christian Boutin, Jam
es
and Anna, Rich and Sharon, Liz and Peter, Rob Fearon (the curator of all things shiny), everyone on Twitter who RTs my babble (you know who you are, guys!), Matthew Smith (the creator of Manic Miner), David Braben, Tōru Iwatani, and anyone who made Atari gam
es
in the 1980s. I would like to thank everyone at AK Peters/CRC Pr
es
s for the help and support and for publishing my work. Finally, a massive thank you go
es
out to you for buying this book and for w
ant
ing to do something as cool as to make gam
es
. I sincerely hope this book helps your gamemaking adventur
es
—feel free to tell me about them on Twitter @psychicparrot or drop by my website at http://www.psychicparrot.com. Acknowledgments xv As I was starting out as a game developer, as a self-taught programmer my skills took a while to reach a level where I could achieve what I w
ant
ed. Sometim
es
I w
ant
ed to do things that I just didn’t have yet the technical skills to achieve. Now and again, software packag
es
came along that could either help me in my qu
es
t to make gam
es
or even make full gam
es
for me; complete game systems such as the Shoot ’Em-Up Construction Kit (aka SEUCK) from Sensible Software, Gary Kitchen’s GameMaker, or The Quill Adventure System could bring to life the kinds of gam
es
that went way beyond anything that my limited programming skills could ever dream of building. The downside to using game creation software was that it was tailored to create gam
es
within their chosen specific genre. If I w
ant
ed to do something outside of the limitations of the software, the source code was inacc
es
sible and there was no way to extend or modify it. When that happened, I longed for a modular code-based system that I could plug together to create different typ
es
of gam
es
but modify parts of it without having to spend a lot of time learning how the entire system internals work—building block game development that I could actually script and modify if I needed to. After completing my first book, Game Development for iOS with Unity3D, I w
ant
ed to follow up by applying a modular style of game building to Unity3D that would provide readers with a highly flexible framework to create just about any kind of game by “plugging in” the different script components. My intention was to make a more technical second book, based on C# programming, that would offer extensibility in any direction a developer might require. In
es
sence, what you are holding in your hands right now is a cookbook Introduction xvi Introduction for game development that has a highly flexible core framework for just about any type of game. A lot of the work I put in at the start of writing this book was in d
es
igning a framework that not only made sense in the context of Unity but also could easily cope with the demands of different genr
es
. Prerequisit
es
You can get up and running with the required software for the grand total of zero dollars. Everything you need can be downloaded free of charge with no catch
es
. You may w
ant
to consider an upgrade to Unity Pro at some point in the future, to take adv
ant
age of some of its advanced featur
es
, but to get started all you need to do is grab the free version from the Unity website. Unity Free or Unity Pro (available from the Unity store at http://www.unity3d.com) Unity Free is completely free for anyone or any company making l
es
s than $100,000 per year—it may be downloaded for no charge at all, and you don’t even need a credit card. It’s a really sweet deal! We are talking about a fully functional game engine, ready to make 3D or 2D gam
es
that may be sold commercially or otherwise. There are no royalti
es
to pay, either. Unity Pro adds a whole host of prof
es
sional functionality to the engine, such as render culling and profiling. If you are a company with more than $100,000 per year of turnover, you will need a Pro license, but if you find that Unity Free do
es
n’t pack quite enough power, you may also w
ant
to consider going Pro. You can arrange a free trial of the Pro version right from the Unity website to try before you buy. If the trial licence runs out before you feel you know enough to make a purchase, contact Unity about extending it and they are usually very friendly and helpful about it (just don’t try using a trial license for 6 months at a time, as they may just figure it out!). C# programming knowledge Again, to reiterate this very import
ant
point, this is nota book about learning how to program. You will need to know some C#, and there are a number of other books out there for that purpose, even if I have tried to make the exampl
es
as simple as possible! This book is about making gam
es
, not about learning to program. What This Book Do
es
n’t Cover This is not a book about programming and it is not a book about the right or wrong way to do things. We assume that the reader has some experience with the C# programming language. I am a self-taught programmer, and I understand that there may well be better ways to do things. xvii Introduction This is a book about concepts, and it is inevitable that there will be better methods for achieving some of the same goals. The techniqu
es
and concepts offered in this book are me
ant
to provide solid foundation, not to be the final word on any subject. It is the author’s intention that, as you gain your own experienc
es
in game development, you make your own rul
es
and draw your own conclusions. Additional material is available from the CRC Pr
es
s Web site: http://www.crcpr
es
s. com/product/isbn/9781466581401. 1 1 Making Gam
es
the Modular Way When I first started making gam
es
, I would approach development on a project-to-project basis, recoding and rebuilding everything from scratch each time. As I became a prof
es
sional developer, landing a job at a game development studio making browser-based gam
es
, I was lucky enough to work with a guy who was innovating the scene. He was a master at turning out great gam
es
(both visually and gameplay-wise) very quickly. One secret to his succ
es
s lay in the development of a reusable framework that could easily be refactored to use on all of his projects. His framework was set up to deal with server communication, input handling, browser communication, and UI among other things, saving an incredible amount of time in putting together all of the
es
sentials. By reusing the framework, it allowed more time for him and his team to concentrate on great gameplay and graphics optimization, r
es
ulting in gam
es
that, at the time, blew the competition away. Of course, the structure was tailored to how he worked (he did build it, after all), and it took me a while to get to grips with his style of development; but once I did, it really opened my ey
es
. From then on, I used the framework for every project and even taught other programmers how to go about using it. Development time was subst
ant
ially reduced, which left more time to concentrate on making better gam
es
. This book is based on a similar concept of a game-centric framework for use with many different typ
es
of gam
es
, rather than a set of different gam
es
in different styl
es
. The overall goal of this book is to provide script-based components that you can use within that framework to make a head start with your own projects in a way that reduc
es
recoding, repurposing, or adaptation time. 2 1. Making Gam
es
the Modular Way In terms of this book as a cookbook, think of the framework as a base soup and the scripting components as ingredients. We can mix and match script components from different gam
es
that use the same framework to make new gam
es
, and we can share several of the same core scripts in many different gam
es
. The framework tak
es
care of the
es
sentials, and we add a little “glue” code to pull everything together the way we w
ant
it all to work. This framework is, of course, optional, but you should spend some time familiarizing yourself with it to help understand the book. If you intend to use the components in this book for your own gam
es
, the framework may serve either as a base to build your gam
es
on or simply as a tutorial t
es
t bed for you to rip apart and see how things work. Perhaps you can develop a better framework or maybe you already have a solid framework in place. If you do, find a way to develop a cleaner, more efficient framework or even a framework that isn’t quite so efficient but works better with your own code, and do it. In this chapter, we start by examining some of the major programming concepts used in this book and look at how they affect the d
es
ign decisions of the framework. 1.1 Import
ant
Programming Concepts I had been programming in C# for a fairly long time before I actually sat down and figured out some of the concepts covered in this chapter. It was not because of any particular problem or difficulty with the concepts themselv
es
but more because I had solved the problems in a different way that me
ant
I had no real requirement to learn anything new. For most programmers, th
es
e concepts will be second nature and perhaps something taught in school, but I did not know how import
ant
they could be. I had heard about things like inheritance, and it was something I put in the to-do list, buried somewhere under “finish the project.” Once I took the time to figure them out, they saved me a lot of time and led to much cleaner code than I would have previously pulled together. If there’s something you are unsure about, give this chapter a read-through and see whether you can work through the ideas. Hopefully, they may save some of you some time in the long run. 1.1.1 Manager and Controller Scripts I am a strong believer in manager and controller scripts. I like to try and split things out into separate areas; for example, in the Metal Vehicle Doomgame, I have race controller scripts and a global race controller script. The race controller scripts are attached to the players and track their positions on the track, waypoints, and other relev
ant
player-specific race information. The global race controller script talks to all the race controller scripts attached to the players to determine who is winning and when the race starts or finish
es
. By keeping this logic separate from the other game scripts and contained in their own controller scripts, it mak
es
it easier to migrate them from project to project.
Es
sentially, I can take the race controller and global race controller scripts out of the game and apply them to another game, perhaps one that featur
es
a completely different type of gameplay— for example, alien characters running around a track
inst
ead of cars. As long as I apply the correct control scripts, the race logic is in place, and I can acc
es
s it in the new game. In the framework that this book contains, there are individual manager and controller scripts dealing with user data, input, game functions, and user interface. We look at those in detail in Chapter 2, but as you read this chapter, you should keep in mind the idea of separated scripts dedicated to managing particular parts of the game structure. It was 3 1.1 Import
ant
Programming Concepts import
ant
to me to d
es
ign scripts as standalone so that they may be used in more than one situation. For example, our weapon slot manager will not care what kind of weapon is in any of the slots. The weapon slot manager is merely an interface between the player and the weapon, taking a call to “fire” and r
es
ponding to it by telling the weapon in the currently selected weapon slot to fire. What happens on the player end will not affect the slot manager just as anything that happens with the weapon itself will not affect the slot manager. It just do
es
n’t care as long as your code talks to it in the proper way and as long as your weapons receive commands in the proper way. It do
es
n’t even matter what type of object the slot manager is attached to. If you decide to attach the weapon slot manager to a car, a boat, a telegraph pole, etc., it do
es
n’t really matter just as long as when you w
ant
them to fire, you use the correct function in the slot manager to get it to tell a weapon to fire. Since our core game logic is controlled by manager and controller scripts, we need to be a little smart about how we piece everything together. Some manager scripts may benefit from being static and available globally (for all other scripts to acc
es
s), whereas others may be better attached to other scripts. We deal with th
es
e on a case-by-case basis. To get things started, we will be looking at some of the ways that th
es
e manager scripts can communicate with each other. As a final note for the topic in this section, you may be wondering what the difference is between managers and controllers. There really isn’t all that much, and I have only chosen to differentiate for my own sanity. I see controllers as scripts that are larger global systems, such as game state control, and managers as smaller scripts applied to gameObjects, such as weapon slot management or physics control. The terms are applied loosely, so don’t worry if there appear to be inconsistenci
es
in the application of the term in one case versus another. I’ll try my b
es
t to keep things logical, but that do
es
n’t mean it’ll always make sense to everyone else! 1.1.2 Script Communication An import
ant
part of our manager- and component-based structur
es
is how our scripts are going to communicate with each other. It is inevitable that we will need to acc
es
s our scripts from a multitude of other areas of the game, which means we should try to provide interfac
es
that make the most sense. There are several different ways of communicating between scripts and objects in Unity: 1. Direct referencing manager scripts via variabl
es
set in the editor by the Inspector window. The easi
es
t way to have your scripts talk to each other is to have direct referenc
es
to them in the form of public variabl
es
within a
class
. They are populated in the Unity editor with a direct link to another script. Here is an example of direct referencing: public void aScript otherScript; In the editor window, the Inspector shows the otherScript field. We drag and drop an object containing the script component that we w
ant
to talk to. Within the
class
, function calls are made directly on the variable, such as otherScript.DoSomething(); 4 1. Making Gam
es
the Modular Way 2. GameObject referencing using SendM
es
sage. SendM
es
sage is a great way to send a m
es
sage to a gameObject and call a function in one of its attached scripts or components when we do not need any kind of return r
es
ult. For example, SomeGameObject.SendM
es
sage("DoSomething"); SendM
es
sage may also take several parameters, such as setting whether or not the engine should throw an error when there is no receiver, that is, no function in any script attached to the gameObject with a name matching the one in the SendM
es
sage call. (SendM
es
sageOptions). You can also pass one parameter into the chosen function just as if you were passing it via a regular function call such as SomeGameObject.SendM
es
sage("AddScore",2); SomeGameObject.SendM
es
sage("AddScore", SendM
es
sageOptions.RequireReceiver); SomeGameObject.SendM
es
sage("AddScore", SendM
es
sageOptions.DontRequireReceiver); 3. Static variabl
es
. The static variable type is useful in that it extends across the entire system; it will be acc
es
sible in every other script. This is a particularly useful behavior for a game control script, where several different scripts may w
ant
to communicate with it to do things such as add to the player’s score, lose a life, or perhaps change a level. An example declaration of a static variable might be private static GameController aController; Although static variabl
es
extend across the entire program, you can have private and public static variabl
es
. Things get a little tricky when you try to understand the differenc
es
between public and private static typ
es
—I was glad to have friends on Twitter that could explain it all to me, so let me pass on what I was told: Public static A public static variable exists everywhere in the system and may be acc
es
sed from other
class
es
and other typ
es
of script. Imagine a situation where a player control script needs to tell the game controller script whenever a player picks up a banana. We could deal with it like this: 1. In our gamecontroller.cs game controller script, we set up a public static: public static GameController gateway; 2. When the game controller (gamecontroller.cs) runs its Start() function, it stor
es
a reference to itself in a public static variable like this: gateway = this; 3. In any other
class
, we can now acc
es
s the game controller by referring to its type followed by that static variable (GameController.gateway) such as GameController.gateway.GotBanana(); 5 1.1 Import
ant
Programming Concepts Private static A private static variable exists within the
class
it was declared and in any other
inst
anc
es
of the same
class
. Other
class
es
/typ
es
of script will not be able to acc
es
s it. As a working example, try to imagine that a script named player.cs directly controls player objects in your game. They all need to tell a player manager script when something happens, so we declare the player manager as a static variable in our player.cs script like this: private static PlayerManager playerManager; The playerManager object only needs to be set up once, by a single
inst
ance of the player
class
, to be ready to use for all the other
inst
anc
es
of the same
class
. All player.cs scripts will be able to acc
es
s the same
inst
ance of the PlayerManager. 4. The singleton d
es
ign pattern. In the previous part of this section, we looked at using a static variable to share a manager script across the entire game code. The bigg
es
t danger with this method is that it is possible to create multiple
inst
anc
es
of the same script. If this happens, you may find that your player code is talking to the wrong
inst
ance of the game controller. A singletonis a commonly used d
es
ign pattern that allows for only one
inst
ance of a particular
class
to be
inst
ant
iated
at a time. This pattern is ideal for our game scripts that may need to communicate (or be communicated with) across the entire game code. Note that we will be providing a static reference to the script, exactly as we did in the “Static Variabl
es
” method earlier in this section, but in implementing a singleton
class
, we will be adding some extra code to make sure that only one
inst
ance of our script is ever created. 1.1.3 Using the Singleton Pattern in Unity It is not too difficult to see how useful static variabl
es
can be in communication between different script objects. In the public static example cited earlier, the idea was that we had a game controller object that needed to be acc
es
sed from one or more other scripts in our game. The method shown here was demonstrated on the Unity public wiki*by a user named Emil Johansen (Angry
Ant
). It us
es
a private static variable in conjunction with a public static function. Other scripts acc
es
s the public function to gain acc
es
s to the private static
inst
ance of this script, which is returned via the public function so that only one
inst
ance of the object will ever exist in a scene regardl
es
s of how many components it is attached to and regardl
es
s of how many tim
es
it is
inst
ant
iated
. A simple singleton structure: public
class
MySingleton { private static MySingleton
inst
ance; public MySingleton () *http://wiki.unity3d.com/index.php/Singleton. 6 1. Making Gam
es
the Modular Way { if (
inst
ance != null) { Debug.LogError ("Cannot have two
inst
anc
es
of singleton."); return; }
inst
ance = this; } public static MySingleton
Inst
ance { get { if (
inst
ance == null) { new MySingleton (); } return
inst
ance; } } } The singleton
inst
ance of our script may be acc
es
sed anywhere, by any script, simply with the
following
syntax: MySingleton.
Inst
ance.MySingletonMember; 1.1.4 Inheritance Inheritanceis a complex concept, which demands some explanation here because of its key role within the scripts provided in this book. Have a read through this section, but don’t worry if you don’t pick up inheritance right away. Once we get to the programming, it will most likely become clear. The bottom line is that inheritance is used in programming to d
es
cribe a method of providing template scripts that may be overridden, or added to, by other scripts. As a metaphor, imagine a car. All cars have four wheels and an engine. The typ
es
of wheels may vary from car to car, as will the engine, so when we say “this is a car” and try to d
es
cribe how our car behav
es
, we may also d
es
cribe the engine and wheels. Th
es
e relationships may be shown in a hierarchical order: Car -Wheels -Engine Now try to picture this as a C# script: Car
class
Wheels function Engine function 7 1.1 Import
ant
Programming Concepts
一个win32下的ARM开源编译器
FASMARM v1.42 This package is an ARM assembler add-on for FASM. FASMARM currently supports the full range of
inst
ructions for 32-bit and 64-bit ARM proc
es
sors and coproc
es
sors up to and including v8. Contents: 1. ARM assembly compatibility 2. UAL and pre-UAL syntax
es
3. IT block handling 4. Alternate encodings 5. Output formats 6. Control directiv
es
7. Data definitions 8. Defining registers lists inside macros 9. Half-precision number formatting 10. Vari
ant
s supported 11. Further information 12. Version history _______________________________________________________________________________ 1. ARM assembly compatibility There are a few r
es
trictions how the ARM
inst
ruction set is implemented. The chang
es
are minor and mostly have a minor impact. For the most part the basic
inst
ruction outline is the same. Where possible the original style is used but there are some differenc
es
: Not everything match
es
the ARM ADS assembly style, where possible the original style is used but there are some differenc
es
1) label nam
es
cannot begin with a digit 2) CPSIE and CPSID formats are changed, use "iflags_aif" form
inst
ead of "aif" (eg. "CPSIE iflags_i"
inst
ead of "CPSID i") 3) SRS with writeback must have a separating space after the mode number and before "!" (eg. "SRSDB 16 !"
inst
ead of "SRSDB 16!") 4) macro, rept, irp, format, if, virtual etc. are all signific
ant
chang
es
from the ARM ADS, so you will need to re-write those sections of existing code Original ARM Syntax | fasmarm Syntax ----------------------+---------------------- cpsie a | cpsie iflags_a | srsdb #29! | srsdb #29 ! ;or, | srsdb 29 ! _______________________________________________________________________________ 2. UAL and pre-UAL syntax
es
fasmarm supports the original pre-UAL syntax and the newer UAL syntax. Th
es
e two syntax
es
only affect THUMB encodings. UAL stands for: Universal Assembly Language. pre-UAL syntax is selected wi
php.ini-development
[PHP] ;;;;;;;;;;;;;;;;;;; ; About php.ini ; ;;;;;;;;;;;;;;;;;;; ; PHP's initialization file, generally called php.ini, is r
es
ponsible for ; configuring many of the aspects of PHP's behavior. ; PHP attempts to find and load this configuration from a number of locations. ; The
following
is a summary of its search order: ; 1. S
API
module specific location. ; 2. The PHPRC environment variable. (As of PHP 5.2.0) ; 3. A number of predefined registry keys on Windows (As of PHP 5.2.0) ; 4. Current working directory (except CLI) ; 5. The web server's directory (for S
API
modul
es
), or directory of PHP ; (otherwise in Windows) ; 6. The directory from the --with-config-file-path compile time option, or the ; Windows directory (C:\windows or C:\winnt) ; See the PHP docs for more specific information. ; http://php.net/configuration.file ; The syntax of the file is extremely simple. Whit
es
pace and lin
es
; beginning with a semicolon are silently ignored (as you probably gu
es
sed). ; Section headers (e.g. [Foo]) are also silently ignored, even though ; they might mean something in the future. ; Directiv
es
following
the section heading [PATH=/www/mysite] only ; apply to PHP fil
es
in the /www/mysite directory. Directiv
es
;
following
the section heading [HOST=www.example.com] only apply to ; PHP fil
es
served from www.example.com. Directiv
es
set in th
es
e ; special sections cannot be overridden by user-defined INI fil
es
or ; at runtime. Currently, [PATH=] and [HOST=] sections only work under ; CGI/FastCGI. ; http://php.net/ini.sections ; Directiv
es
are specified using the
following
syntax: ; directive = value ; Directive nam
es
are *case sensitive* - foo=bar is different from FOO=bar. ; Directiv
es
are variabl
es
used to configure PHP or PHP extensions. ; There is no name validation. If PHP can't find an expected ; directive because it is not set or is mistyped, a default value will be used. ; The value can be a string, a number, a PHP const
ant
(e.g. E_ALL or M_PI), one ; of the INI const
ant
s (On, Off, True, False, Y
es
, No and None) or an expr
es
sion ; (e.g. E_ALL & ~E_NOTICE), a quoted string ("bar"), or a reference to a ; previously set variable or directive (e.g. ${foo}) ; Expr
es
sions in the INI file are limited to bitwise operators and parenth
es
es
: ; | bitwise OR ; ^ bitwise XOR ; & bitwise AND ; ~ bitwise NOT ; ! boolean NOT ; Boolean flags can be turned on using the valu
es
1, On, True or Y
es
. ; They can be turned off using the valu
es
0, Off, False or No. ; An empty string can be denoted by simply not writing anything after the equal ; sign, or by using the None keyword: ; foo = ; sets foo to an empty string ; foo = None ; sets foo to an empty string ; foo = "None" ; sets foo to the string 'None' ; If you use const
ant
s in your value, and th
es
e const
ant
s belong to a ; dynamically loaded extension (either a PHP extension or a Zend extension), ; you may only use th
es
e const
ant
s *after* the line that loads the extension. ;;;;;;;;;;;;;;;;;;; ; About this file ; ;;;;;;;;;;;;;;;;;;; ; PHP com
es
packaged with two INI fil
es
. One that is recommended to be used ; in production environments and one that is recommended to be used in ; development environments. ; php.ini-production contains settings which hold security, performance and ; b
es
t practic
es
at its core. But please be aware, th
es
e settings may break ; compatibility with older or l
es
s security conscience applications. We ; recommending using the production ini in production and t
es
ting environments. ; php.ini-development is very similar to its production vari
ant
, except it's ; much more verbose when it com
es
to errors. We recommending using the ; development version only in development environments as errors shown to ; application users can inadvertently leak otherwise secure information. ; This is php.ini-development INI file. ;;;;;;;;;;;;;;;;;;; ; Quick Reference ; ;;;;;;;;;;;;;;;;;;; ; The
following
are all the settings which are different in either the production ; or development versions of the INIs with r
es
pect to PHP's default behavior. ; Please see the actual settings later in the document for more details as to why ; we recommend th
es
e chang
es
in PHP's behavior. ; display_errors ; Default Value: On ; Development Value: On ; Production Value: Off ; display_startup_errors ; Default Value: Off ; Development Value: On ; Production Value: Off ; error_reporting ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED ; Development Value: E_ALL ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT ; html_errors ; Default Value: On ; Development Value: On ; Production value: On ; log_errors ; Default Value: Off ; Development Value: On ; Production Value: On ; max_input_time ; Default Value: -1 (Unlimited) ; Development Value: 60 (60 seconds) ; Production Value: 60 (60 seconds) ; output_buffering ; Default Value: Off ; Development Value: 4096 ; Production Value: 4096 ; register_argc_argv ; Default Value: On ; Development Value: Off ; Production Value: Off ; requ
es
t_order ; Default Value: None ; Development Value: "GP" ; Production Value: "GP" ; s
es
sion.gc_divisor ; Default Value: 100 ; Development Value: 1000 ; Production Value: 1000 ; s
es
sion.hash_bits_per_character ; Default Value: 4 ; Development Value: 5 ; Production Value: 5 ; short_open_tag ; Default Value: On ; Development Value: Off ; Production Value: Off ; track_errors ; Default Value: Off ; Development Value: On ; Production Value: Off ; url_rewriter.tags ; Default Value: "a=href,area=href,frame=src,form=,fieldset=" ; Development Value: "a=href,area=href,frame=src,input=src,form=fakeentry" ; Production Value: "a=href,area=href,frame=src,input=src,form=fakeentry" ; variabl
es
_order ; Default Value: "EGPCS" ; Development Value: "GPCS" ; Production Value: "GPCS" ;;;;;;;;;;;;;;;;;;;; ; php.ini Options ; ;;;;;;;;;;;;;;;;;;;; ; Name for user-defined php.ini (.htacc
es
s) fil
es
. Default is ".user.ini" ;user_ini.filename = ".user.ini" ; To disable this feature set this option to empty value ;user_ini.filename = ; TTL for user-defined php.ini fil
es
(time-to-live) in seconds. Default is 300 seconds (5 minut
es
) ;user_ini.cache_ttl = 300 ;;;;;;;;;;;;;;;;;;;; ; Language Options ; ;;;;;;;;;;;;;;;;;;;; ; Enable the PHP scripting language engine under Apache. ; http://php.net/engine engine = On ; This directive determin
es
whether or not PHP will recognize code between ; and ?> tags as PHP source which should be proc
es
sed as such. It is ; generally recommended that should be used and that this feature ; should be disabled, as enabling it may r
es
ult in issu
es
when generating XML ; documents, however this remains supported for backward compatibility reasons. ; Note that this directive do
es
not control the = shorthand tag, which can be ; used regardl
es
s of this directive. ; Default Value: On ; Development Value: Off ; Production Value: Off ; http://php.net/short-open-tag short_open_tag = Off ; Allow ASP-style <% %> tags. ; http://php.net/asp-tags asp_tags = Off ; The number of signific
ant
digits displayed in floating point numbers. ; http://php.net/precision precision = 14 ; Output buffering is a mechanism for controlling how much output data ; (excluding headers and cooki
es
) PHP should keep internally before pushing that ; data to the client. If your application's output exceeds this setting, PHP ; will send that data in chunks of roughly the size you specify. ; Turning on this setting and managing its maximum buffer size can yield some ; inter
es
ting side-effects depending on your application and web server. ; You may be able to send headers and cooki
es
after you've already sent output ; through print or echo. You also may see performance benefits if your server is ; emitting l
es
s packets due to buffered output versus PHP streaming the output ; as it gets it. On production servers, 4096 byt
es
is a good setting for performance ; reasons. ; Note: Output buffering can also be controlled via Output Buffering Control ; functions. ; Possible Valu
es
: ; On = Enabled and buffer is unlimited. (Use with caution) ; Off = Disabled ; Integer = Enabl
es
the buffer and sets its maximum size in byt
es
. ; Note: This directive is hardcoded to Off for the CLI S
API
; Default Value: Off ; Development Value: 4096 ; Production Value: 4096 ; http://php.net/output-buffering output_buffering = 4096 ; You can redirect all of the output of your scripts to a function. For ; example, if you set output_handler to "mb_output_handler", character ; encoding will be transparently converted to the specified encoding. ; Setting any output handler automatically turns on output buffering. ; Note: People who wrote portable scripts should not depend on this ini ; directive.
Inst
ead, explicitly set the output handler using ob_start(). ; Using this ini directive may cause problems unl
es
s you know what script ; is doing. ; Note: You cannot use both "mb_output_handler" with "ob_iconv_handler" ; and you cannot use both "ob_gzhandler" and "zlib.output_compr
es
sion". ; Note: output_handler must be empty if this is set 'On' !!!! ;
Inst
ead you must use zlib.output_handler. ; http://php.net/output-handler ;output_handler = ; Transparent output compr
es
sion using the zlib library ; Valid valu
es
for this option are 'off', 'on', or a specific buffer size ; to be used for compr
es
sion (default is 4KB) ; Note: R
es
ulting chunk size may vary due to nature of compr
es
sion. PHP ; outputs chunks that are few hundreds byt
es
each as a r
es
ult of ; compr
es
sion. If you prefer a larger chunk size for better ; performance, enable output_buffering in addition. ; Note: You need to use zlib.output_handler
inst
ead of the standard ; output_handler, or otherwise the output will be corrupted. ; http://php.net/zlib.output-compr
es
sion zlib.output_compr
es
sion = Off ; http://php.net/zlib.output-compr
es
sion-level ;zlib.output_compr
es
sion_level = -1 ; You cannot specify additional output handlers if zlib.output_compr
es
sion ; is activated here. This setting do
es
the same as output_handler but in ; a different order. ; http://php.net/zlib.output-handler ;zlib.output_handler = ; Implicit flush tells PHP to tell the output layer to flush itself ; automatically after every output block. This is equivalent to calling the ; PHP function flush() after each and every call to print() or echo() and each ; and every HTML block. Turning this option on has serious performance ; implications and is generally recommended for debugging purpos
es
only. ; http://php.net/implicit-flush ; Note: This directive is hardcoded to On for the CLI S
API
implicit_flush = Off ; The unserialize callback function will be called (with the undefined
class
' ; name as parameter), if the unserializer finds an undefined
class
; which should be
inst
ant
iated
. A warning appears if the specified function is ; not defined, or if the function do
es
n't include/implement the missing
class
. ; So only set this entry, if you really w
ant
to implement such a ; callback-function. unserialize_callback_func = ; When floats & doubl
es
are serialized store serialize_precision signific
ant
; digits after the floating point. The default value ensur
es
that when floats ; are decoded with unserialize, the data will remain the same. serialize_precision = 17 ; open_basedir, if set, limits all file operations to the defined directory ; and below. This directive mak
es
most sense if used in a per-directory ; or per-virtualhost web server configuration file. This directive is ; *NOT* affected by whether Safe Mode is turned On or Off. ; http://php.net/open-basedir ;open_basedir = ; This directive allows you to disable certain functions for security reasons. ; It receiv
es
a comma-delimited list of function nam
es
. This directive is ; *NOT* affected by whether Safe Mode is turned On or Off. ; http://php.net/disable-functions disable_functions = ; This directive allows you to disable certain
class
es
for security reasons. ; It receiv
es
a comma-delimited list of
class
nam
es
. This directive is ; *NOT* affected by whether Safe Mode is turned On or Off. ; http://php.net/disable-
class
es
disable_
class
es
= ; Colors for Syntax Highlighting mode. Anything that's acceptable in ;
would work. ; http://php.net/syntax-highlighting ;highlight.string = #DD0000 ;highlight.comment = #FF9900 ;highlight.keyword = #007700 ;highlight.default = #0000BB ;highlight.html = #000000 ; If enabled, the requ
es
t will be allowed to complete even if the user aborts ; the requ
es
t. Consider enabling it if executing long requ
es
ts, which may end up ; being interrupted by the user or a browser timing out. PHP's default behavior ; is to disable this feature. ; http://php.net/ignore-user-abort ;ignore_user_abort = On ; Determin
es
the size of the realpath cache to be used by PHP. This value should ; be increased on systems where PHP opens many fil
es
to reflect the qu
ant
ity of ; the file operations performed. ; http://php.net/realpath-cache-size ;realpath_cache_size = 16k ; Duration of time, in seconds for which to cache realpath information for a given ; file or directory. For systems with rarely changing fil
es
, consider increasing this ; value. ; http://php.net/realpath-cache-ttl ;realpath_cache_ttl = 120 ; Enabl
es
or disabl
es
the circular reference collector. ; http://php.net/zend.enable-gc zend.enable_gc = On ; If enabled, scripts may be written in encodings that are incompatible with ; the scanner. CP936, Big5, CP949 and Shift_JIS are the exampl
es
of such ; encodings. To use this feature, mbstring extension must be enabled. ; Default: Off ;zend.multibyte = Off ; Allows to set the default encoding for the scripts. This value will be used ; unl
es
s "declare(encoding=...)" directive appears at the top of the script. ; Only affects if zend.multibyte is set. ; Default: "" ;zend.script_encoding = ;;;;;;;;;;;;;;;;; ; Miscellaneous ; ;;;;;;;;;;;;;;;;; ; Decid
es
whether PHP may expose the fact that it is
inst
alled on the server ; (e.g. by adding its signature to the Web server header). It is no security ; threat in any way, but it mak
es
it possible to determine whether you use PHP ; on your server or not. ; http://php.net/expose-php expose_php = On ;;;;;;;;;;;;;;;;;;; ; R
es
ource Limits ; ;;;;;;;;;;;;;;;;;;; ; Maximum execution time of each script, in seconds ; http://php.net/max-execution-time ; Note: This directive is hardcoded to 0 for the CLI S
API
max_execution_time = 30 ; Maximum amount of time each script may spend parsing requ
es
t data. It's a good ; idea to limit this time on productions servers in order to eliminate unexpectedly ; long running scripts. ; Note: This directive is hardcoded to -1 for the CLI S
API
; Default Value: -1 (Unlimited) ; Development Value: 60 (60 seconds) ; Production Value: 60 (60 seconds) ; http://php.net/max-input-time max_input_time = 60 ; Maximum input variable n
es
ting level ; http://php.net/max-input-n
es
ting-level ;max_input_n
es
ting_level = 64 ; How many GET/POST/COOKIE input variabl
es
may be accepted ; max_input_vars = 1000 ; Maximum amount of memory a script may consume (128MB) ; http://php.net/memory-limit memory_limit = 128M ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Error handling and logging ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; This directive informs PHP of which errors, warnings and notic
es
you would like ; it to take action for. The recommended way of setting valu
es
for this ; directive is through the use of the error level const
ant
s and bitwise ; operators. The error level const
ant
s are below here for convenience as well as ; some common settings and their meanings. ; By default, PHP is set to take action on all errors, notic
es
and warnings EXCEPT ; those related to E_NOTICE and E_STRICT, which together cover b
es
t practic
es
and ; recommended coding standards in PHP. For performance reasons, this is the ; recommend error reporting setting. Your production server shouldn't be wasting ; r
es
ourc
es
complaining about b
es
t practic
es
and coding standards. That's what ; development servers and development settings are for. ; Note: The php.ini-development file has this setting as E_ALL. This ; means it pretty much reports everything which is exactly what you w
ant
during ; development and early t
es
ting. ; ; Error Level Const
ant
s: ; E_ALL - All errors and warnings (includ
es
E_STRICT as of PHP 5.4.0) ; E_ERROR - fatal run-time errors ; E_RECOVERABLE_ERROR - almost fatal run-time errors ; E_WARNING - run-time warnings (non-fatal errors) ; E_PARSE - compile-time parse errors ; E_NOTICE - run-time notic
es
(th
es
e are warnings which often r
es
ult ; from a bug in your code, but it's possible that it was ; intentional (e.g., using an uninitialized variable and ; relying on the fact it's automatically initialized to an ; empty string) ; E_STRICT - run-time notic
es
, enable to have PHP sugg
es
t chang
es
; to your code which will ensure the b
es
t interoperability ; and forward compatibility of your code ; E_CORE_ERROR - fatal errors that occur during PHP's initial startup ; E_CORE_WARNING - warnings (non-fatal errors) that occur during PHP's ; initial startup ; E_COMPILE_ERROR - fatal compile-time errors ; E_COMPILE_WARNING - compile-time warnings (non-fatal errors) ; E_USER_ERROR - user-generated error m
es
sage ; E_USER_WARNING - user-generated warning m
es
sage ; E_USER_NOTICE - user-generated notice m
es
sage ; E_DEPRECATED - warn about code that will not work in future versions ; of PHP ; E_USER_DEPRECATED - user-generated deprecation warnings ; ; Common Valu
es
: ; E_ALL (Show all errors, warnings and notic
es
including coding standards.) ; E_ALL & ~E_NOTICE (Show all errors, except for notic
es
) ; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notic
es
and coding standards warnings.) ; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors) ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED ; Development Value: E_ALL ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT ; http://php.net/error-reporting error_reporting = E_ALL ; This directive controls whether or not and where PHP will output errors, ; notic
es
and warnings too. Error output is very useful during development, but ; it could be very dangerous in production environments. Depending on the code ; which is triggering the error, sensitive information could potentially leak ; out of your application such as database usernam
es
and passwords or worse. ; It's recommended that errors be logged on production servers rather than ; having the errors sent to STDOUT. ; Possible Valu
es
: ; Off = Do not display any errors ; stderr = Display errors to STDERR (affects only CGI/CLI binari
es
!) ; On or stdout = Display errors to STDOUT ; Default Value: On ; Development Value: On ; Production Value: Off ; http://php.net/display-errors display_errors = On ; The display of errors which occur during PHP's startup sequence are handled ; separately from display_errors. PHP's default behavior is to suppr
es
s those ; errors from clients. Turning the display of startup errors on can be useful in ; debugging configuration problems. But, it's strongly recommended that you ; leave this setting off on production servers. ; Default Value: Off ; Development Value: On ; Production Value: Off ; http://php.net/display-startup-errors display_startup_errors = On ; B
es
id
es
displaying errors, PHP can also log errors to locations such as a ; server-specific log, STDERR, or a location specified by the error_log ; directive found below. While errors should not be displayed on productions ; servers they should still be monitored and logging is a great way to do that. ; Default Value: Off ; Development Value: On ; Production Value: On ; http://php.net/log-errors log_errors = On ; Set maximum length of log_errors. In error_log information about the source is ; added. The default is 1024 and 0 allows to not apply any maximum length at all. ; http://php.net/log-errors-max-len log_errors_max_len = 1024 ; Do not log repeated m
es
sag
es
. Repeated errors must occur in same file on same ; line unl
es
s ignore_repeated_source is set true. ; http://php.net/ignore-repeated-errors ignore_repeated_errors = Off ; Ignore source of m
es
sage when ignoring repeated m
es
sag
es
. When this setting ; is On you will not log errors with repeated m
es
sag
es
from different fil
es
or ; source lin
es
. ; http://php.net/ignore-repeated-source ignore_repeated_source = Off ; If this parameter is set to Off, then memory leaks will not be shown (on ; stdout or in the log). This has only effect in a debug compile, and if ; error reporting includ
es
E_WARNING in the allowed list ; http://php.net/report-memleaks report_memleaks = On ; This setting is on by default. ;report_zend_debug = 0 ; Store the last error/warning m
es
sage in $php_errormsg (boolean). Setting this value ; to On can assist in debugging and is appropriate for development servers. It should ; however be disabled on production servers. ; Default Value: Off ; Development Value: On ; Production Value: Off ; http://php.net/track-errors track_errors = On ; Turn off normal error reporting and emit XML-RPC error XML ; http://php.net/xmlrpc-errors ;xmlrpc_errors = 0 ; An XML-RPC faultCode ;xmlrpc_error_number = 0 ; When PHP displays or logs an error, it has the capability of formatting the ; error m
es
sage as HTML for easier reading. This directive controls whether ; the error m
es
sage is formatted as HTML or not. ; Note: This directive is hardcoded to Off for the CLI S
API
; Default Value: On ; Development Value: On ; Production value: On ; http://php.net/html-errors html_errors = On ; If html_errors is set to On *and* docref_root is not empty, then PHP ; produc
es
clickable error m
es
sag
es
that direct to a page d
es
cribing the error ; or function causing the error in detail. ; You can download a copy of the PHP manual from http://php.net/docs ; and change docref_root to the base URL of your local copy including the ; leading '/'. You must also specify the file extension being used including ; the dot. PHP's default behavior is to leave th
es
e settings empty, in which ; case no links to documentation are generated. ; Note: Never use this feature for production box
es
. ; http://php.net/docref-root ; Exampl
es
;docref_root = "/phpmanual/" ; http://php.net/docref-ext ;docref_ext = .html ; String to output before an error m
es
sage. PHP's default behavior is to leave ; this setting blank. ; http://php.net/error-prepend-string ; Example: ;error_prepend_string = "
" ; String to output after an error m
es
sage. PHP's default behavior is to leave ; this setting blank. ; http://php.net/error-append-string ; Example: ;error_append_string = "
" ; Log errors to specified file. PHP's default behavior is to leave this value ; empty. ; http://php.net/error-log ; Example: ;error_log = php_errors.log ; Log errors to syslog (Event Log on Windows). ;error_log = syslog ;windows.show_crt_warning ; Default value: 0 ; Development value: 0 ; Production value: 0 ;;;;;;;;;;;;;;;;; ; Data Handling ; ;;;;;;;;;;;;;;;;; ; The separator used in PHP generated URLs to separate arguments. ; PHP's default setting is "&". ; http://php.net/arg-separator.output ; Example: ;arg_separator.output = "&" ; List of separator(s) used by PHP to parse input URLs into variabl
es
. ; PHP's default setting is "&". ; NOTE: Every character in this directive is considered as separator! ; http://php.net/arg-separator.input ; Example: ;arg_separator.input = ";&" ; This directive determin
es
which super global arrays are registered when PHP ; starts up. G,P,C,E & S are abbreviations for the
following
r
es
pective super ; globals: GET, POST, COOKIE, ENV and SERVER. There is a performance penalty ; paid for the registration of th
es
e arrays and because ENV is not as commonly ; used as the others, ENV is not recommended on productions servers. You ; can still get acc
es
s to the environment variabl
es
through getenv() should you ; need to. ; Default Value: "EGPCS" ; Development Value: "GPCS" ; Production Value: "GPCS"; ; http://php.net/variabl
es
-order variabl
es
_order = "GPCS" ; This directive determin
es
which super global data (G,P,C,E & S) should ; be registered into the super global array REQU
ES
T. If so, it also determin
es
; the order in which that data is registered. The valu
es
for this directive are ; specified in the same manner as the variabl
es
_order directive, EXCEPT one. ; Leaving this value empty will cause PHP to use the value set in the ; variabl
es
_order directive. It do
es
not mean it will leave the super globals ; array REQU
ES
T empty. ; Default Value: None ; Development Value: "GP" ; Production Value: "GP" ; http://php.net/requ
es
t-order requ
es
t_order = "GP" ; This directive determin
es
whether PHP registers $argv & $argc each time it ; runs. $argv contains an array of all the arguments passed to PHP when a script ; is invoked. $argc contains an integer repr
es
enting the number of arguments ; that were passed when the script was invoked. Th
es
e arrays are extremely ; useful when running scripts from the command line. When this directive is ; enabled, registering th
es
e variabl
es
consum
es
CPU cycl
es
and memory each time ; a script is executed. For performance reasons, this feature should be disabled ; on production servers. ; Note: This directive is hardcoded to On for the CLI S
API
; Default Value: On ; Development Value: Off ; Production Value: Off ; http://php.net/register-argc-argv register_argc_argv = Off ; When enabled, the ENV, REQU
ES
T and SERVER variabl
es
are created when they're ; first used (Just In Time)
inst
ead of when the script starts. If th
es
e ; variabl
es
are not used within a script, having this directive on will r
es
ult ; in a performance gain. The PHP directive register_argc_argv must be disabled ; for this directive to have any affect. ; http://php.net/auto-globals-jit auto_globals_jit = On ; Whether PHP will read the POST data. ; This option is enabled by default. ; Most likely, you won't w
ant
to disable this option globally. It caus
es
$_POST ; and $_FIL
ES
to always be empty; the only way you will be able to read the ; POST data will be through the php://input stream wrapper. This can be useful ; to proxy requ
es
ts or to proc
es
s the POST data in a memory efficient fashion. ; http://php.net/enable-post-data-reading ;enable_post_data_reading = Off ; Maximum size of POST data that PHP will accept. ; Its value may be 0 to disable the limit. It is ignored if POST data reading ; is disabled through enable_post_data_reading. ; http://php.net/post-max-size post_max_size = 8M ; Automatically add fil
es
before PHP document. ; http://php.net/auto-prepend-file auto_prepend_file = ; Automatically add fil
es
after PHP document. ; http://php.net/auto-append-file auto_append_file = ; By default, PHP will output a character encoding using ; the Content-type: header. To disable sending of the charset, simply ; set it to be empty. ; ; PHP's built-in default is text/html ; http://php.net/default-mimetype default_mimetype = "text/html" ; PHP's default character set is set to empty. ; http://php.net/default-charset ;default_charset = "UTF-8" ; Always populate the $HTTP_RAW_POST_DATA variable. PHP's default behavior is ; to disable this feature. If post reading is disabled through ; enable_post_data_reading, $HTTP_RAW_POST_DATA is *NOT* populated. ; http://php.net/always-populate-raw-post-data ;always_populate_raw_post_data = On ;;;;;;;;;;;;;;;;;;;;;;;;; ; Paths and Directori
es
; ;;;;;;;;;;;;;;;;;;;;;;;;; ; UNIX: "/path1:/path2" ;include_path = ".:/php/includ
es
" ; ; Windows: "\path1;\path2" ;include_path = ".;c:\php\includ
es
" ; ; PHP's default setting for include_path is ".;/path/to/php/pear" ; http://php.net/include-path ; The root of the PHP pag
es
, used only if nonempty. ; if PHP was not compiled with FORCE_REDIRECT, you SHOULD set doc_root ; if you are running php as a CGI under any web server (other than IIS) ; see documentation for security issu
es
. The alternate is to use the ; cgi.force_redirect configuration below ; http://php.net/doc-root doc_root = ; The directory under which PHP opens the script using /~username used only ; if nonempty. ; http://php.net/user-dir user_dir = ; Directory in which the loadable extensions (modul
es
) r
es
ide. ; http://php.net/extension-dir ; extension_dir = "./" ; On windows: ; extension_dir = "ext" ; Whether or not to enable the dl() function. The dl() function do
es
NOT work ; properly in multithreaded servers, such as IIS or Zeus, and is automatically ; disabled on them. ; http://php.net/enable-dl enable_dl = Off ; cgi.force_redirect is nec
es
sary to provide security running PHP as a CGI under ; most web servers. Left undefined, PHP turns this on by default. You can ; turn it off here AT YOUR OWN RISK ; **You CAN safely turn this off for IIS, in fact, you MUST.** ; http://php.net/cgi.force-redirect ;cgi.force_redirect = 1 ; if cgi.nph is enabled it will force cgi to always sent Status: 200 with ; every requ
es
t. PHP's default behavior is to disable this feature. ;cgi.nph = 1 ; if cgi.force_redirect is turned on, and you are not running under Apache or Netscape ; (iPlanet) web servers, you MAY need to set an environment variable name that PHP ; will look for to know it is OK to continue execution. Setting this variable MAY ; cause security issu
es
, KNOW WHAT YOU ARE DOING FIRST. ; http://php.net/cgi.redirect-status-env ;cgi.redirect_status_env = ; cgi.fix_pathinfo provid
es
*real* PATH_INFO/PATH_TRANSLATED support for CGI. PHP's ; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok ; what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting ; this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting ; of zero caus
es
PHP to behave as before. Default is 1. You should fix your scripts ; to use SCRIPT_FILENAME rather than PATH_TRANSLATED. ; http://php.net/cgi.fix-pathinfo ;cgi.fix_pathinfo=1 ; FastCGI under IIS (on WINNT based OS) supports the ability to impersonate ; security tokens of the calling client. This allows IIS to define the ; security context that the requ
es
t runs under. mod_fastcgi under Apache ; do
es
not currently support this feature (03/17/2002) ; Set to 1 if running under IIS. Default is zero. ; http://php.net/fastcgi.impersonate ;fastcgi.impersonate = 1 ; Disable logging through FastCGI connection. PHP's default behavior is to enable ; this feature. ;fastcgi.logging = 0 ; cgi.rfc2616_headers configuration option tells PHP what type of headers to ; use when sending HTTP r
es
ponse code. If it's set 0 PHP sends Status: header that ; is supported by Apache. When this option is set to 1 PHP will send ; RFC2616 compli
ant
header. ; Default is zero. ; http://php.net/cgi.rfc2616-headers ;cgi.rfc2616_headers = 0 ;;;;;;;;;;;;;;;; ; File Uploads ; ;;;;;;;;;;;;;;;; ; Whether to allow HTTP file uploads. ; http://php.net/file-uploads file_uploads = On ; Temporary directory for HTTP uploaded fil
es
(will use system default if not ; specified). ; http://php.net/upload-tmp-dir ;upload_tmp_dir = ; Maximum allowed size for uploaded fil
es
. ; http://php.net/upload-max-fil
es
ize upload_max_fil
es
ize = 2M ; Maximum number of fil
es
that can be uploaded via a single requ
es
t max_file_uploads = 20 ;;;;;;;;;;;;;;;;;; ; Fopen wrappers ; ;;;;;;;;;;;;;;;;;; ; Whether to allow the treatment of URLs (like http:// or ftp://) as fil
es
. ; http://php.net/allow-url-fopen allow_url_fopen = On ; Whether to allow include/require to open URLs (like http:// or ftp://) as fil
es
. ; http://php.net/allow-url-include allow_url_include = Off ; Define the anonymous ftp password (your email addr
es
s). PHP's default setting ; for this is empty. ; http://php.net/from ;from="john@doe.com" ; Define the User-Agent string. PHP's default setting for this is empty. ; http://php.net/user-agent ;user_agent="PHP" ; Default timeout for socket based streams (seconds) ; http://php.net/default-socket-timeout default_socket_timeout = 60 ; If your scripts have to deal with fil
es
from Macintosh systems, ; or you are running on a Mac and need to deal with fil
es
from ; unix or win32 systems, setting this flag will cause PHP to ; automatically detect the EOL character in those fil
es
so that ; fgets() and file() will work regardl
es
s of the source of the file. ; http://php.net/auto-detect-line-endings ;auto_detect_line_endings = Off ;;;;;;;;;;;;;;;;;;;;;; ; Dynamic Extensions ; ;;;;;;;;;;;;;;;;;;;;;; ; If you wish to have an extension loaded automatically, use the
following
; syntax: ; ; extension=modulename.extension ; ; For example, on Windows: ; ; extension=msql.dll ; ; ... or under UNIX: ; ; extension=msql.so ; ; ... or with a path: ; ; extension=/path/to/extension/msql.so ; ; If you only provide the name of the extension, PHP will look for it in its ; default extension directory. ; ; Windows Extensions ; Note that ODBC support is built in, so no dll is needed for it. ; Note that many DLL fil
es
are located in the extensions/ (PHP 4) ext/ (PHP 5) ; extension folders as well as the separate PECL DLL download (PHP 5). ; Be sure to appropriately set the extension_dir directive. ; ;extension=php_bz2.dll ;extension=php_curl.dll ;extension=php_fileinfo.dll ;extension=php_gd2.dll ;extension=php_gettext.dll ;extension=php_gmp.dll ;extension=php_intl.dll ;extension=php_imap.dll ;extension=php_interbase.dll ;extension=php_ldap.dll ;extension=php_mbstring.dll ;extension=php_exif.dll ; Must be after mbstring as it depends on it ;extension=php_mysql.dll ;extension=php_mysqli.dll ;extension=php_oci8.dll ; Use with Oracle 10gR2
Inst
ant
Client ;extension=php_oci8_11g.dll ; Use with Oracle 11gR2
Inst
ant
Client ;extension=php_openssl.dll ;extension=php_pdo_firebird.dll ;extension=php_pdo_mysql.dll ;extension=php_pdo_oci.dll ;extension=php_pdo_odbc.dll ;extension=php_pdo_pgsql.dll ;extension=php_pdo_sqlite.dll ;extension=php_pgsql.dll ;extension=php_pspell.dll ;extension=php_shmop.dll ; The MIBS data available in the PHP distribution must be
inst
alled. ; See http://www.php.net/manual/en/snmp.
inst
allation.php ;extension=php_snmp.dll ;extension=php_soap.dll ;extension=php_sockets.dll ;extension=php_sqlite3.dll ;extension=php_sybase_ct.dll ;extension=php_tidy.dll ;extension=php_xmlrpc.dll ;extension=php_xsl.dll ;;;;;;;;;;;;;;;;;;; ; Module Settings ; ;;;;;;;;;;;;;;;;;;; [CLI Server] ; Whether the CLI web server us
es
ANSI color coding in its terminal output. cli_server.color = On [Date] ; Defin
es
the default timezone used by the date functions ; http://php.net/date.timezone ;date.timezone = ; http://php.net/date.default-latitude ;date.default_latitude = 31.7667 ; http://php.net/date.default-longitude ;date.default_longitude = 35.2333 ; http://php.net/date.sunrise-zenith ;date.sunrise_zenith = 90.583333 ; http://php.net/date.sunset-zenith ;date.sunset_zenith = 90.583333 [filter] ; http://php.net/filter.default ;filter.default = unsafe_raw ; http://php.net/filter.default-flags ;filter.default_flags = [iconv] ;iconv.input_encoding = ISO-8859-1 ;iconv.internal_encoding = ISO-8859-1 ;iconv.output_encoding = ISO-8859-1 [intl] ;intl.default_locale = ; This directive allows you to produce PHP errors when some error ; happens within intl functions. The value is the level of the error produced. ; Default is 0, which do
es
not produce any errors. ;intl.error_level = E_WARNING [sqlite] ; http://php.net/sqlite.assoc-case ;sqlite.assoc_case = 0 [sqlite3] ;sqlite3.extension_dir = [Pcre] ;PCRE library backtracking limit. ; http://php.net/pcre.backtrack-limit ;pcre.backtrack_limit=100000 ;PCRE library recursion limit. ;Please note that if you set this value to a high number you may consume all ;the available proc
es
s stack and eventually crash PHP (due to reaching the ;stack size limit imposed by the Operating System). ; http://php.net/pcre.recursion-limit ;pcre.recursion_limit=100000 [Pdo] ; Whether to pool ODBC connections. Can be one of "strict", "relaxed" or "off" ; http://php.net/pdo-odbc.connection-pooling ;pdo_odbc.connection_pooling=strict ;pdo_odbc.db2_
inst
ance_name [Pdo_mysql] ; If mysqlnd is used: Number of cache slots for the internal r
es
ult set cache ; http://php.net/pdo_mysql.cache_size pdo_mysql.cache_size = 2000 ; Default socket name for local MySQL connects. If empty, us
es
the built-in ; MySQL defaults. ; http://php.net/pdo_mysql.default-socket pdo_mysql.default_socket= [Phar] ; http://php.net/phar.readonly ;phar.readonly = On ; http://php.net/phar.require-hash ;phar.require_hash = On ;phar.cache_list = [mail function] ; For Win32 only. ; http://php.net/smtp SMTP = localhost ; http://php.net/smtp-port smtp_port = 25 ; For Win32 only. ; http://php.net/sendmail-from ;sendmail_from = me@example.com ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). ; http://php.net/sendmail-path ;sendmail_path = ; Force the addition of the specified parameters to be passed as extra parameters ; to the sendmail binary. Th
es
e parameters will always replace the value of ; the 5th parameter to mail(), even in safe mode. ;mail.force_extra_parameters = ; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename mail.add_x_header = On ; The path to a log file that will log all mail() calls. Log entri
es
include ; the full path of the script, line number, To addr
es
s and headers. ;mail.log = ; Log mail to syslog (Event Log on Windows). ;mail.log = syslog [SQL] ; http://php.net/sql.safe-mode sql.safe_mode = Off [ODBC] ; http://php.net/odbc.default-db ;odbc.default_db = Not yet implemented ; http://php.net/odbc.default-user ;odbc.default_user = Not yet implemented ; http://php.net/odbc.default-pw ;odbc.default_pw = Not yet implemented ; Controls the ODBC cursor model. ; Default: SQL_CURSOR_STATIC (default). ;odbc.default_cursortype ; Allow or prevent persistent links. ; http://php.net/odbc.allow-persistent odbc.allow_persistent = On ; Check that a connection is still valid before reuse. ; http://php.net/odbc.check-persistent odbc.check_persistent = On ; Maximum number of persistent links. -1 means no limit. ; http://php.net/odbc.max-persistent odbc.max_persistent = -1 ; Maximum number of links (persistent + non-persistent). -1 means no limit. ; http://php.net/odbc.max-links odbc.max_links = -1 ; Handling of LONG fields. Returns number of byt
es
to variabl
es
. 0 means ; passthru. ; http://php.net/odbc.defaultlrl odbc.defaultlrl = 4096 ; Handling of binary data. 0 means passthru, 1 return as is, 2 convert to char. ; See the documentation on odbc_binmode and odbc_longreadlen for an explanation ; of odbc.defaultlrl and odbc.defaultbinmode ; http://php.net/odbc.defaultbinmode odbc.defaultbinmode = 1 ;birdstep.max_links = -1 [Interbase] ; Allow or prevent persistent links. ibase.allow_persistent = 1 ; Maximum number of persistent links. -1 means no limit. ibase.max_persistent = -1 ; Maximum number of links (persistent + non-persistent). -1 means no limit. ibase.max_links = -1 ; Default database name for ibase_connect(). ;ibase.default_db = ; Default username for ibase_connect(). ;ibase.default_user = ; Default password for ibase_connect(). ;ibase.default_password = ; Default charset for ibase_connect(). ;ibase.default_charset = ; Default tim
es
tamp format. ibase.tim
es
tampformat = "%Y-%m-%d %H:%M:%S" ; Default date format. ibase.dateformat = "%Y-%m-%d" ; Default time format. ibase.timeformat = "%H:%M:%S" [MySQL] ; Allow acc
es
sing, from PHP's perspective, local fil
es
with LOAD DATA statements ; http://php.net/mysql.allow_local_infile mysql.allow_local_infile = On ; Allow or prevent persistent links. ; http://php.net/mysql.allow-persistent mysql.allow_persistent = On ; If mysqlnd is used: Number of cache slots for the internal r
es
ult set cache ; http://php.net/mysql.cache_size mysql.cache_size = 2000 ; Maximum number of persistent links. -1 means no limit. ; http://php.net/mysql.max-persistent mysql.max_persistent = -1 ; Maximum number of links (persistent + non-persistent). -1 means no limit. ; http://php.net/mysql.max-links mysql.max_links = -1 ; Default port number for mysql_connect(). If unset, mysql_connect() will use ; the $MYSQL_TCP_PORT or the mysql-tcp entry in /etc/servic
es
or the ; compile-time value defined MYSQL_PORT (in that order). Win32 will only look ; at MYSQL_PORT. ; http://php.net/mysql.default-port mysql.default_port = ; Default socket name for local MySQL connects. If empty, us
es
the built-in ; MySQL defaults. ; http://php.net/mysql.default-socket mysql.default_socket = ; Default host for mysql_connect() (do
es
n't apply in safe mode). ; http://php.net/mysql.default-host mysql.default_host = ; Default user for mysql_connect() (do
es
n't apply in safe mode). ; http://php.net/mysql.default-user mysql.default_user = ; Default password for mysql_connect() (do
es
n't apply in safe mode). ; Note that this is generally a *bad* idea to store passwords in this file. ; *Any* user with PHP acc
es
s can run 'echo get_cfg_var("mysql.default_password") ; and reveal this password! And of course, any users with read acc
es
s to this ; file will be able to reveal the password as well. ; http://php.net/mysql.default-password mysql.default_password = ; Maximum time (in seconds) for connect timeout. -1 means no limit ; http://php.net/mysql.connect-timeout mysql.connect_timeout = 60 ; Trace mode. When trace_mode is active (=On), warnings for table/index scans and ; SQL-Errors will be displayed. ; http://php.net/mysql.trace-mode mysql.trace_mode = Off [MySQLi] ; Maximum number of persistent links. -1 means no limit. ; http://php.net/mysqli.max-persistent mysqli.max_persistent = -1 ; Allow acc
es
sing, from PHP's perspective, local fil
es
with LOAD DATA statements ; http://php.net/mysqli.allow_local_infile ;mysqli.allow_local_infile = On ; Allow or prevent persistent links. ; http://php.net/mysqli.allow-persistent mysqli.allow_persistent = On ; Maximum number of links. -1 means no limit. ; http://php.net/mysqli.max-links mysqli.max_links = -1 ; If mysqlnd is used: Number of cache slots for the internal r
es
ult set cache ; http://php.net/mysqli.cache_size mysqli.cache_size = 2000 ; Default port number for mysqli_connect(). If unset, mysqli_connect() will use ; the $MYSQL_TCP_PORT or the mysql-tcp entry in /etc/servic
es
or the ; compile-time value defined MYSQL_PORT (in that order). Win32 will only look ; at MYSQL_PORT. ; http://php.net/mysqli.default-port mysqli.default_port = 3306 ; Default socket name for local MySQL connects. If empty, us
es
the built-in ; MySQL defaults. ; http://php.net/mysqli.default-socket mysqli.default_socket = ; Default host for mysql_connect() (do
es
n't apply in safe mode). ; http://php.net/mysqli.default-host mysqli.default_host = ; Default user for mysql_connect() (do
es
n't apply in safe mode). ; http://php.net/mysqli.default-user mysqli.default_user = ; Default password for mysqli_connect() (do
es
n't apply in safe mode). ; Note that this is generally a *bad* idea to store passwords in this file. ; *Any* user with PHP acc
es
s can run 'echo get_cfg_var("mysqli.default_pw") ; and reveal this password! And of course, any users with read acc
es
s to this ; file will be able to reveal the password as well. ; http://php.net/mysqli.default-pw mysqli.default_pw = ; Allow or prevent reconnect mysqli.reconnect = Off [mysqlnd] ; Enable / Disable collection of general statistics by mysqlnd which can be ; used to tune and monitor MySQL operations. ; http://php.net/mysqlnd.collect_statistics mysqlnd.collect_statistics = On ; Enable / Disable collection of memory usage statistics by mysqlnd which can be ; used to tune and monitor MySQL operations. ; http://php.net/mysqlnd.collect_memory_statistics mysqlnd.collect_memory_statistics = On ; Size of a pre-allocated buffer used when sending commands to MySQL in byt
es
. ; http://php.net/mysqlnd.net_cmd_buffer_size ;mysqlnd.net_cmd_buffer_size = 2048 ; Size of a pre-allocated buffer used for reading data sent by the server in ; byt
es
. ; http://php.net/mysqlnd.net_read_buffer_size ;mysqlnd.net_read_buffer_size = 32768 [OCI8] ; Connection: Enabl
es
privileged connections using external ; credentials (OCI_SYSOPER, OCI_SYSDBA) ; http://php.net/oci8.privileged-connect ;oci8.privileged_connect = Off ; Connection: The maximum number of persistent OCI8 connections per ; proc
es
s. Using -1 means no limit. ; http://php.net/oci8.max-persistent ;oci8.max_persistent = -1 ; Connection: The maximum number of seconds a proc
es
s is allowed to ; maintain an idle persistent connection. Using -1 means idle ; persistent connections will be maintained forever. ; http://php.net/oci8.persistent-timeout ;oci8.persistent_timeout = -1 ; Connection: The number of seconds that must pass before issuing a ; ping during oci_pconnect() to check the connection validity. When ; set to 0, each oci_pconnect() will cause a ping. Using -1 disabl
es
; pings completely. ; http://php.net/oci8.ping-interval ;oci8.ping_interval = 60 ; Connection: Set this to a user chosen connection
class
to be used ; for all pooled server requ
es
ts with Oracle 11g Database R
es
ident ; Connection Pooling (DRCP). To use DRCP, this value should be set to ; the same string for all web servers running the same application, ; the database pool must be configured, and the connection string must ; specify to use a pooled server. ;oci8.connection_
class
= ; High Availability: Using On lets PHP receive Fast Application ; Notification (FAN) events generated when a database node fails. The ; database must also be configured to post FAN events. ;oci8.events = Off ; Tuning: This option enabl
es
statement caching, and specifi
es
how ; many statements to cache. Using 0 disabl
es
statement caching. ; http://php.net/oci8.statement-cache-size ;oci8.statement_cache_size = 20 ; Tuning: Enabl
es
statement prefetching and sets the default number of ; rows that will be fetched automatically after statement execution. ; http://php.net/oci8.default-prefetch ;oci8.default_prefetch = 100 ; Compatibility. Using On means oci_close() will not close ; oci_connect() and oci_new_connect() connections. ; http://php.net/oci8.old-oci-close-sem
ant
ics ;oci8.old_oci_close_sem
ant
ics = Off [Postgr
eS
QL] ; Allow or prevent persistent links. ; http://php.net/pgsql.allow-persistent pgsql.allow_persistent = On ; Detect broken persistent links always with pg_pconnect(). ; Auto r
es
et feature requir
es
a little overheads. ; http://php.net/pgsql.auto-r
es
et-persistent pgsql.auto_r
es
et_persistent = Off ; Maximum number of persistent links. -1 means no limit. ; http://php.net/pgsql.max-persistent pgsql.max_persistent = -1 ; Maximum number of links (persistent+non persistent). -1 means no limit. ; http://php.net/pgsql.max-links pgsql.max_links = -1 ; Ignore Postgr
eS
QL backends Notice m
es
sage or not. ; Notice m
es
sage logging require a little overheads. ; http://php.net/pgsql.ignore-notice pgsql.ignore_notice = 0 ; Log Postgr
eS
QL backends Notice m
es
sage or not. ; Unl
es
s pgsql.ignore_notice=0, module cannot log notice m
es
sage. ; http://php.net/pgsql.log-notice pgsql.log_notice = 0 [Sybase-CT] ; Allow or prevent persistent links. ; http://php.net/sybct.allow-persistent sybct.allow_persistent = On ; Maximum number of persistent links. -1 means no limit. ; http://php.net/sybct.max-persistent sybct.max_persistent = -1 ; Maximum number of links (persistent + non-persistent). -1 means no limit. ; http://php.net/sybct.max-links sybct.max_links = -1 ; Minimum server m
es
sage severity to display. ; http://php.net/sybct.min-server-severity sybct.min_server_severity = 10 ; Minimum client m
es
sage severity to display. ; http://php.net/sybct.min-client-severity sybct.min_client_severity = 10 ; Set per-context timeout ; http://php.net/sybct.timeout ;sybct.timeout= ;sybct.packet_size ; The maximum time in seconds to wait for a connection attempt to succeed before returning failure. ; Default: one minute ;sybct.login_timeout= ; The name of the host you claim to be connecting from, for display by sp_who. ; Default: none ;sybct.hostname= ; Allows you to define how often deadlocks are to be retried. -1 means "forever". ; Default: 0 ;sybct.deadlock_retry_count= [bcmath] ; Number of decimal digits for all bcmath functions. ; http://php.net/bcmath.scale bcmath.scale = 0 [browscap] ; http://php.net/browscap ;browscap = extra/browscap.ini [S
es
sion] ; Handler used to store/retrieve data. ; http://php.net/s
es
sion.save-handler s
es
sion.save_handler = fil
es
; Argument passed to save_handler. In the case of fil
es
, this is the path ; where data fil
es
are stored. Note: Windows users have to change this ; variable in order to use PHP's s
es
sion functions. ; ; The path can be defined as: ; ; s
es
sion.save_path = "N;/path" ; ; where N is an integer.
Inst
ead of storing all the s
es
sion fil
es
in ; /path, what this will do is use subdirectori
es
N-levels deep, and ; store the s
es
sion data in those directori
es
. This is useful if you ; or your OS have problems with lots of fil
es
in one directory, and is ; a more efficient layout for servers that handle lots of s
es
sions. ; ; NOTE 1: PHP will not create this directory structure automatically. ; You can use the script in the ext/s
es
sion dir for that purpose. ; NOTE 2: See the section on garbage collection below if you choose to ; use subdirectori
es
for s
es
sion storage ; ; The file storage module creat
es
fil
es
using mode 600 by default. ; You can change that by using ; ; s
es
sion.save_path = "N;MODE;/path" ; ; where MODE is the octal repr
es
entation of the mode. Note that this ; do
es
not overwrite the proc
es
s's umask. ; http://php.net/s
es
sion.save-path ;s
es
sion.save_path = "/tmp" ; Whether to use cooki
es
. ; http://php.net/s
es
sion.use-cooki
es
s
es
sion.use_cooki
es
= 1 ; http://php.net/s
es
sion.cookie-secure ;s
es
sion.cookie_secure = ; This option forc
es
PHP to fetch and use a cookie for storing and maintaining ; the s
es
sion id. We encourage this operation as it's very helpful in combating ; s
es
sion hijacking when not specifying and managing your own s
es
sion id. It is ; not the end all be all of s
es
sion hijacking defense, but it's a good start. ; http://php.net/s
es
sion.use-only-cooki
es
s
es
sion.use_only_cooki
es
= 1 ; Name of the s
es
sion (used as cookie name). ; http://php.net/s
es
sion.name s
es
sion.name = PHPS
ES
SID ; Initialize s
es
sion on requ
es
t startup. ; http://php.net/s
es
sion.auto-start s
es
sion.auto_start = 0 ; Lifetime in seconds of cookie or, if 0, until browser is r
es
tarted. ; http://php.net/s
es
sion.cookie-lifetime s
es
sion.cookie_lifetime = 0 ; The path for which the cookie is valid. ; http://php.net/s
es
sion.cookie-path s
es
sion.cookie_path = / ; The domain for which the cookie is valid. ; http://php.net/s
es
sion.cookie-domain s
es
sion.cookie_domain = ; Whether or not to add the httpOnly flag to the cookie, which mak
es
it inacc
es
sible to browser scripting languag
es
such as JavaScript. ; http://php.net/s
es
sion.cookie-httponly s
es
sion.cookie_httponly = ; Handler used to serialize data. php is the standard serializer of PHP. ; http://php.net/s
es
sion.serialize-handler s
es
sion.serialize_handler = php ; Defin
es
the probability that the 'garbage collection' proc
es
s is started ; on every s
es
sion initialization. The probability is calculated by using ; gc_probability/gc_divisor. Where s
es
sion.gc_probability is the numerator ; and gc_divisor is the denominator in the equation. Setting this value to 1 ; when the s
es
sion.gc_divisor value is 100 will give you approximately a 1% chance ; the gc will run on any give requ
es
t. ; Default Value: 1 ; Development Value: 1 ; Production Value: 1 ; http://php.net/s
es
sion.gc-probability s
es
sion.gc_probability = 1 ; Defin
es
the probability that the 'garbage collection' proc
es
s is started on every ; s
es
sion initialization. The probability is calculated by using the
following
equation: ; gc_probability/gc_divisor. Where s
es
sion.gc_probability is the numerator and ; s
es
sion.gc_divisor is the denominator in the equation. Setting this value to 1 ; when the s
es
sion.gc_divisor value is 100 will give you approximately a 1% chance ; the gc will run on any give requ
es
t. Increasing this value to 1000 will give you ; a 0.1% chance the gc will run on any give requ
es
t. For high volume production servers, ; this is a more efficient approach. ; Default Value: 100 ; Development Value: 1000 ; Production Value: 1000 ; http://php.net/s
es
sion.gc-divisor s
es
sion.gc_divisor = 1000 ; After this number of seconds, stored data will be seen as 'garbage' and ; cleaned up by the garbage collection proc
es
s. ; http://php.net/s
es
sion.gc-maxlifetime s
es
sion.gc_maxlifetime = 1440 ; NOTE: If you are using the subdirectory option for storing s
es
sion fil
es
; (see s
es
sion.save_path above), then garbage collection do
es
*not* ; happen automatically. You will need to do your own garbage ; collection through a shell script, cron entry, or some other method. ; For example, the
following
script would is the equivalent of ; setting s
es
sion.gc_maxlifetime to 1440 (1440 seconds = 24 minut
es
): ; find /path/to/s
es
sions -cmin +24 -type f | xargs rm ; Check HTTP Referer to invalidate externally stored URLs containing ids. ; HTTP_REFERER has to contain this substring for the s
es
sion to be ; considered as valid. ; http://php.net/s
es
sion.referer-check s
es
sion.referer_check = ; How many byt
es
to read from the file. ; http://php.net/s
es
sion.entropy-length ;s
es
sion.entropy_length = 32 ; Specified here to create the s
es
sion id. ; http://php.net/s
es
sion.entropy-file ; Defaults to /dev/urandom ; On systems that don't have /dev/urandom but do have /dev/arandom, this will default to /dev/arandom ; If neither are found at compile time, the default is no entropy file. ; On windows, setting the entropy_length setting will activate the ; Windows random source (using the Crypto
API
) ;s
es
sion.entropy_file = /dev/urandom ; Set to {nocache,private,public,} to determine HTTP caching aspects ; or leave this empty to avoid sending
ant
i-caching headers. ; http://php.net/s
es
sion.cache-limiter s
es
sion.cache_limiter = nocache ; Document expir
es
after n minut
es
. ; http://php.net/s
es
sion.cache-expire s
es
sion.cache_expire = 180 ; trans sid support is disabled by default. ; Use of trans sid may risk your users security. ; Use this option with caution. ; - User may send URL contains active s
es
sion ID ; to other person via. email/irc/etc. ; - URL that contains active s
es
sion ID may be stored ; in publicly acc
es
sible computer. ; - User may acc
es
s your site with the same s
es
sion ID ; always using URL stored in browser's history or bookmarks. ; http://php.net/s
es
sion.use-trans-sid s
es
sion.use_trans_sid = 0 ; Select a hash function for use in generating s
es
sion ids. ; Possible Valu
es
; 0 (MD5 128 bits) ; 1 (SHA-1 160 bits) ; This option may also be set to the name of any hash function supported by ; the hash extension. A list of available hash
es
is returned by the hash_algos() ; function. ; http://php.net/s
es
sion.hash-function s
es
sion.hash_function = 0 ; Define how many bits are stored in each character when converting ; the binary hash data to something readable. ; Possible valu
es
: ; 4 (4 bits: 0-9, a-f) ; 5 (5 bits: 0-9, a-v) ; 6 (6 bits: 0-9, a-z, A-Z, "-", ",") ; Default Value: 4 ; Development Value: 5 ; Production Value: 5 ; http://php.net/s
es
sion.hash-bits-per-character s
es
sion.hash_bits_per_character = 5 ; The URL rewriter will look for URLs in a defined set of HTML tags. ; form/fieldset are special; if you include them here, the rewriter will ; add a hidden
field with the info which is otherwise appended ; to URLs. If you w
ant
XHTML conformity, remove the form entry. ; Note that all valid entri
es
require a "=", even if no value follows. ; Default Value: "a=href,area=href,frame=src,form=,fieldset=" ; Development Value: "a=href,area=href,frame=src,input=src,form=fakeentry" ; Production Value: "a=href,area=href,frame=src,input=src,form=fakeentry" ; http://php.net/url-rewriter.tags url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry" ; Enable upload progr
es
s tracking in $_S
ES
SION ; Default Value: On ; Development Value: On ; Production Value: On ; http://php.net/s
es
sion.upload-progr
es
s.enabled ;s
es
sion.upload_progr
es
s.enabled = On ; Cleanup the progr
es
s information as soon as all POST data has been read ; (i.e. upload completed). ; Default Value: On ; Development Value: On ; Production Value: On ; http://php.net/s
es
sion.upload-progr
es
s.cleanup ;s
es
sion.upload_progr
es
s.cleanup = On ; A prefix used for the upload progr
es
s key in $_S
ES
SION ; Default Value: "upload_progr
es
s_" ; Development Value: "upload_progr
es
s_" ; Production Value: "upload_progr
es
s_" ; http://php.net/s
es
sion.upload-progr
es
s.prefix ;s
es
sion.upload_progr
es
s.prefix = "upload_progr
es
s_" ; The index name (concatenated with the prefix) in $_S
ES
SION ; containing the upload progr
es
s information ; Default Value: "PHP_S
ES
SION_UPLOAD_PROGR
ES
S" ; Development Value: "PHP_S
ES
SION_UPLOAD_PROGR
ES
S" ; Production Value: "PHP_S
ES
SION_UPLOAD_PROGR
ES
S" ; http://php.net/s
es
sion.upload-progr
es
s.name ;s
es
sion.upload_progr
es
s.name = "PHP_S
ES
SION_UPLOAD_PROGR
ES
S" ; How frequently the upload progr
es
s should be updated. ; Given either in percentag
es
(per-file), or in byt
es
; Default Value: "1%" ; Development Value: "1%" ; Production Value: "1%" ; http://php.net/s
es
sion.upload-progr
es
s.freq ;s
es
sion.upload_progr
es
s.freq = "1%" ; The minimum delay between updat
es
, in seconds ; Default Value: 1 ; Development Value: 1 ; Production Value: 1 ; http://php.net/s
es
sion.upload-progr
es
s.min-freq ;s
es
sion.upload_progr
es
s.min_freq = "1" [MSSQL] ; Allow or prevent persistent links. mssql.allow_persistent = On ; Maximum number of persistent links. -1 means no limit. mssql.max_persistent = -1 ; Maximum number of links (persistent+non persistent). -1 means no limit. mssql.max_links = -1 ; Minimum error severity to display. mssql.min_error_severity = 10 ; Minimum m
es
sage severity to display. mssql.min_m
es
sage_severity = 10 ; Compatibility mode with old versions of PHP 3.0. mssql.compatability_mode = Off ; Connect timeout ;mssql.connect_timeout = 5 ; Query timeout ;mssql.timeout = 60 ; Valid range 0 - 2147483647. Default = 4096. ;mssql.textlimit = 4096 ; Valid range 0 - 2147483647. Default = 4096. ;mssql.textsize = 4096 ; Limits the number of records in each batch. 0 = all records in one batch. ;mssql.batchsize = 0 ; Specify how datetime and datetim4 columns are returned ; On => Returns data converted to SQL server settings ; Off => Returns valu
es
as YYYY-MM-DD hh:mm:ss ;mssql.datetimeconvert = On ; Use NT authentication when connecting to the server mssql.secure_connection = Off ; Specify max number of proc
es
s
es
. -1 = library default ; msdlib defaults to 25 ; FreeTDS defaults to 4096 ;mssql.max_procs = -1 ; Specify client character set. ; If empty or not set the client charset from freetds.conf is used ; This is only used when compiled with FreeTDS ;mssql.charset = "ISO-8859-1" [Assertion] ; Assert(expr); active by default. ; http://php.net/assert.active ;assert.active = On ; Issue a PHP warning for each failed assertion. ; http://php.net/assert.warning ;assert.warning = On ; Don't bail out by default. ; http://php.net/assert.bail ;assert.bail = Off ; User-function to be called if an assertion fails. ; http://php.net/assert.callback ;assert.callback = 0 ; Eval the expr
es
sion with current error_reporting(). Set to true if you w
ant
; error_reporting(0) around the eval(). ; http://php.net/assert.quiet-eval ;assert.quiet_eval = 0 [COM] ; path to a file containing GUIDs, IIDs or filenam
es
of fil
es
with TypeLibs ; http://php.net/com.typelib-file ;com.typelib_file = ; allow Distributed-COM calls ; http://php.net/com.allow-dcom ;com.allow_dcom = true ; autoregister const
ant
s of a components typlib on com_load() ; http://php.net/com.autoregister-typelib ;com.autoregister_typelib = true ; register const
ant
s cas
es
ensitive ; http://php.net/com.autoregister-cas
es
ensitive ;com.autoregister_cas
es
ensitive = false ; show warnings on duplicate const
ant
registrations ; http://php.net/com.autoregister-verbose ;com.autoregister_verbose = true ; The default character set code-page to use when passing strings to and from COM objects. ; Default: system ANSI code page ;com.code_page= [mbstring] ; language for internal character repr
es
entation. ; http://php.net/mbstring.language ;mbstring.language = Japan
es
e ; internal/script encoding. ; Some encoding cannot work as internal encoding. ; (e.g. SJIS, BIG5, ISO-2022-*) ; http://php.net/mbstring.internal-encoding ;mbstring.internal_encoding = EUC-JP ; http input encoding. ; http://php.net/mbstring.http-input ;mbstring.http_input = auto ; http output encoding. mb_output_handler must be ; registered as output buffer to function ; http://php.net/mbstring.http-output ;mbstring.http_output = SJIS ; enable automatic encoding translation according to ; mbstring.internal_encoding setting. Input chars are ; converted to internal encoding by setting this to On. ; Note: Do _not_ use automatic encoding translation for ; portable libs/applications. ; http://php.net/mbstring.encoding-translation ;mbstring.encoding_translation = Off ; automatic encoding detection order. ; auto means ; http://php.net/mbstring.detect-order ;mbstring.detect_order = auto ; substitute_character used when character cannot be converted ; one from another ; http://php.net/mbstring.substitute-character ;mbstring.substitute_character = none; ; overload(replace) single byte functions by mbstring functions. ; mail(), ereg(), etc are overloaded by mb_send_mail(), mb_ereg(), ; etc. Possible valu
es
are 0,1,2,4 or combination of them. ; For example, 7 for overload everything. ; 0: No overload ; 1: Overload mail() function ; 2: Overload str*() functions ; 4: Overload ereg*() functions ; http://php.net/mbstring.func-overload ;mbstring.func_overload = 0 ; enable strict encoding detection. ;mbstring.strict_detection = Off ; This directive specifi
es
the regex pattern of content typ
es
for which mb_output_handler() ; is activated. ; Default: mbstring.http_output_conv_mimetype=^(text/|application/xhtml\+xml) ;mbstring.http_output_conv_mimetype= [gd] ; Tell the jpeg decode to ignore warnings and try to create ; a gd image. The warning will then be displayed as notic
es
; disabled by default ; http://php.net/gd.jpeg-ignore-warning ;gd.jpeg_ignore_warning = 0 [exif] ; Exif UNICODE user comments are handled as UCS-2BE/UCS-2LE and JIS as JIS. ; With mbstring support this will automatically be converted into the encoding ; given by corr
es
ponding encode setting. When empty mbstring.internal_encoding ; is used. For the decode settings you can distinguish between motorola and ; intel byte order. A decode setting cannot be empty. ; http://php.net/exif.encode-unicode ;exif.encode_unicode = ISO-8859-15 ; http://php.net/exif.decode-unicode-motorola ;exif.decode_unicode_motorola = UCS-2BE ; http://php.net/exif.decode-unicode-intel ;exif.decode_unicode_intel = UCS-2LE ; http://php.net/exif.encode-jis ;exif.encode_jis = ; http://php.net/exif.decode-jis-motorola ;exif.decode_jis_motorola = JIS ; http://php.net/exif.decode-jis-intel ;exif.decode_jis_intel = JIS [Tidy] ; The path to a default tidy configuration file to use when using tidy ; http://php.net/tidy.default-config ;tidy.default_config = /usr/local/lib/php/default.tcfg ; Should tidy clean and repair output automatically? ; WARNING: Do not use this option if you are generating non-html content ; such as dynamic imag
es
; http://php.net/tidy.clean-output tidy.clean_output = Off [soap] ; Enabl
es
or disabl
es
WSDL caching feature. ; http://php.net/soap.wsdl-cache-enabled soap.wsdl_cache_enabled=1 ; Sets the directory name where SOAP extension will put cache fil
es
. ; http://php.net/soap.wsdl-cache-dir soap.wsdl_cache_dir="/tmp" ; (time to live) Sets the number of second while cached file will be used ;
inst
ead of original one. ; http://php.net/soap.wsdl-cache-ttl soap.wsdl_cache_ttl=86400 ; Sets the size of the cache limit. (Max. number of WSDL fil
es
to cache) soap.wsdl_cache_limit = 5 [sysvshm] ; A default size of the shared memory segment ;sysvshm.init_mem = 10000 [ldap] ; Sets the maximum number of open links or -1 for unlimited. ldap.max_links = -1 [mcrypt] ; For more information about mcrypt settings see http://php.net/mcrypt-module-open ; Directory where to load mcrypt algorithms ; Default: Compiled in into libmcrypt (usually /usr/local/lib/libmcrypt) ;mcrypt.algorithms_dir= ; Directory where to load mcrypt mod
es
; Default: Compiled in into libmcrypt (usually /usr/local/lib/libmcrypt) ;mcrypt.mod
es
_dir= [dba] ;dba.default_handler= [curl] ; A default value for the CURLOPT_CAINFO option. This is required to be an ; absolute path. ;curl.cainfo = ; Local Variabl
es
: ; tab-width: 4 ; End:
Android
80,351
社区成员
91,288
社区内容
发帖
与我相关
我的任务
Android
移动平台 Android
复制链接
扫一扫
分享
社区描述
移动平台 Android
android
android-studio
androidx
技术论坛(原bbs)
社区管理员
加入社区
获取链接或二维码
近7日
近30日
至今
加载中
查看更多榜单
社区公告
暂无公告
试试用AI创作助手写篇文章吧
+ 用AI写文章