foo.Person person =null;null产品是什么意思思

Cappuccino - Learning Objective-J
Learning Objective-J
Objective-J is a new programming language based on Objective-C. It is a
superset of JavaScript, which means that any valid JavaScript code is
also valid Objective-J code. Anyone familiar with JavaScript and
object-oriented programming concepts, classical inheritance in
particular, should have no difficulty learning Objective-J. Familiarity
with Objective-C will be helpful, but it is not required.
Objective-J has two types of objects: native JavaScript objects and
Objective-J objects. Native JS objects are exactly what they sound like,
the objects native to JavaScript. Objective-J objects are a special type
of native object added by Objective-J. These new objects are based on
classes and classical inheritance, like C++ or Java, instead of the
prototypal model.
Creating a class in Objective-J is simple. Here’s an example of a Person
class that contains one member variable, name:
@implementation Person : CPObject
CPString name;
The beginning of a class is always the keyword @implementation, followed
by the class name. The third term, after the colon, is the class you
want to subclass. In this case, we’re subclassing CPObject, which is the
root class for most classes. You don’t need a superclass, but nearly all
the time you will want one.
After the declaration, a block enclosed with brackets is used to define
all your member variables. Each variable is declared on its own line
with a type and variable name, and a semicolon. Technically the type is
optional, but its highly recommended. Declaring your member variables is
important, because any variable used elsewhere in your class that isn’t
declared will automatically become a global variable.
To end a class declaration, add the keyword @end.
Just as with objects, native JavaScript functions work unchanged in
Objective-J. In addition to native functions, Objective-J adds methods
which are part of the new class system. Let’s add a set of accessor
methods to our Person class:
- (void)setName:(CPString)aName
name = aName;
- (CPString)name
return name;
These lines go anywhere after the initial @implementation line and
instance variable declaration block, but before the @end keyword. This
syntax should be familiar to anyone who’s programmed a C style language
before, including JavaScript. The only interesting thing is the method
declaration.
Each method signature starts with either a dash (-) or a plus (+).
Dashes are used for instance methods, which are methods you can call on
instance variables. Both of our methods above are instance methods,
which makes sense because they set and retrieve instance variables of
our Person objects.
Following the dash/plus is a return type, in parentheses. Nothing
special about this. Again, type declarations are optional but highly
recommended, as they help document your code. Finally, we declare the
method name. In Objective-J, method parameters are interspersed within
the method name. Our two methods above are name, and setName:. Note the
colon after “setName” - it indicates that a parameter follows.
When methods have more than one parameter, each parameter is separated
by a colon. In the declaration of such a method, parameters are split by
a label, followed by a colon, the type, and the parameter name:
- (void)setJobTitle:(CPString)aJobTitle company:(CPString)aCompany
In Objective-J, method names are split across all of the arguments to a
method. These are not technically named arguments. The method above is
named setJobTitle:company:. This is achieved by concatenating the first
part of the method with all the subsequent labels, in order.
The parameters to a method must be passed in order, and all of the
parameters are required. To call such a multiple parameter method, we
pass our data after each label:
[myPerson setJobTitle:"Founder" company:"Cappuccino Foundation"];
As you can see, each colon is followed by the input that will be mapped
to that parameter name. That sequence of label, colon, input is repeated
for each parameter.
You may be wondering why it matters what the actual name of the method
is. One pattern you’ll find in Objective-J and Cappuccino is the idea of
passing a method as an argument to another method. This is used commonly
in delegation and in the event system. Since methods aren’t first class
objects in the same way as JavaScript, we use a special notation to
refer to them, @selector. If I wanted to pass the previous method as an
argument to another method, I would use the following code:
[fooObject setCallbackSelector:@selector(setJobTitle:company:)];
As you can see, the method name is passed to @selector complete with its
colons and parameter labels.
Using Objects & Classes
Now that we’ve covered the basics Objective-J objects and classes, let’s
see how you use them. This block of code creates a new Person object,
and sets the name:
var myPerson = [[Person alloc] init];
[myPerson setName:"John"];
Method calls in Objective-J are called “messages”, and you send an
object a message using bracket notation like this: [object message]. I
mentioned earlier that some methods are class methods, which are meant
to be called on a class itself – alloc is one of these methods. Every
class in Objective-J has a special class method called alloc, which
returns a new instance of that class.
In the example above, we’re calling the alloc method on the Person
class, which returns a Person instance. Then, we call the init method on
that instance. Both alloc and init return a reference to the object,
which we can assign our variable myPerson. Just like alloc, every class
inherits the init method from CPObject.
The alloc class method is analogous to the “new” keyword in many
languages like JavaScript, C++, and Java, in that they create a new
instance. The init instance methods are like the constructors in those
languages, in that they perform initialization on the newly created
Some classes specify their own custom init method, like CPView, which
uses the following signature:
- (id)initWithFrame:(CGRect)aFrame
Every subclass should be sure to call its parent class’s init method.
Here’s a custom init method for our Person class which takes the name
- (id)initWithName:(CPString)aName
self = [super init];
name = aName;
return self;
First we call our superclass init method, which returns a reference to
the newly initialized instance. We must assign this reference to the
self variable (in case the super class’s init method swapped out the
original instance for a new one). We check to make sure self was
returned correctly, and if so we can do our class specific task of
assigning aName to name, and finally, we return self so that calling
code will have a reference to the newly initialized object.
self is the Objective-J equivalent to JavaScript’s this. Just as
this references the JavaScript object, self references the
Objective-J object. Like JavaScript, self.foo will refer to the foo
instance variable, but unlike JavaScript self isn’t required, you can
just use foo within any instance methods.
Many classes in Cappuccino offer a slightly different model for creating
objects, which can be more convenient. Instead of calling alloc and
init, these classes implement their own class method to return new
objects. Note that in class methods, self refers to the class itself.
+ (id)personWithName:(CPString)aName
return [[self alloc] initWithName:aName];
Which would be called like this:
var joe = [Person personWithName:"Joe"];
Importing Code
One commonly desired technique missing from JavaScript is the ability to
import code in the same way that languages like Java or C allow. To that
effect, Objective-J adds the @import statement:
@import &Foundation/CPObject.j&
@import &AppKit/CPView.j&
@import "MyClass.j"
There are two types of import statements. The angle brackets indicate
framework code, while the quotation marks indicate local project code.
Framework imports use the built in search path mechanism to search for
the desired file in any of the defined locations. Local imports only
look in the location relative to the importing file.
Memory Management
JavaScript is garbage collected, and so is Objective-J, so you won’t see
any calls to retain or release in Objective-J code as you would in
Objective-C. Many common leaks caused by DOM manipulation are handled by
the Cappuccino frameworks.
That isn’t to say it’s impossible to leak objects. As with any garbage
collected language, it’s possible to accidentally hold on to reference
to objects such that they can’t be freed, so keep this in mind.
Categories
Categories allow you to add methods to a class without needing to create
a new subclass or modify the class’s source code. The new method (or
methods) become part of all instances of the class once the category is
This is useful in many different scenarios, for example adding methods
to built-in classes. If you wanted all your CPString objects to have a
method that would return the reverse string, you could define a category
like this:
@import &Foundation/CPString.j&
@implementation CPString (Reversing)
- (CPString)reverse
var reversedString = "",
index = [self length];
while(index--)
reversedString += [self characterAtIndex:index];
return reversedString;
Now you can call reverse on any string to get the reversed string.
var myString = "hello world",
reversed = [myString reverse];
alert(reversed);
// alerts "dlrow olleh"
The syntax for the category is @implementation, followed by the class
you’re adding to, followed by the name of your category in parentheses.
Any methods added before the @end keyword will be part of the category.
Note that you can’t add instance variables via categories, though due to
the dynamic nature of JavaScript objects it’s possible to add one by
simply modifying the object’s properties directly:
instance.newProperty = "foo";
It’s interesting to note some of the techniques used in the
implementation of the reverse method above. For example, reversedString
is declared just like any typical JavaScript string. This is thanks to a
technique called toll-free bridging which allows any JavaScript object
like an array or a string to act both as a JavaScript object and a
Cappuccino object at the same time. It responds to CPString methods like
length and characterAtIndex:, as well as existing JavaScript methods
and operators such as +.
Most of the time, Objective-J has the same scoping rules as JavaScript.
Variables not specifically declared with var become globals, while var’d
variables have function/method level scope. The two changes to these
rules are instance variables and file-scoped variables.
Instances variables are declared in the @implementation block, as seen
earlier in the tutorial. When you use those variables within your class,
they have object level scope – they are not global, they belong to each
instance object. If you forget to declare one of your instance
variables, however, then it is treated as a global variable like any
other JavaScript code.
File-scoped variables are something introduced in Objective-J. When you
declare a variable with the var keyword outside a function or method
implementation, these variables (sometimes called statics) have file
level scope. They can only be accessed by other code within the same
file. This can be useful for implementing many shared object techniques
without needing to resort to global variables. If a file contains a
single class they can be thought of as “class variables”.
The following is an example of the main scoping rules in Objective-J:
globalScoped = "this becomes global";
var fileScoped = "this stays scoped in the file";
@implementation Foo : CPObject
CPString objectScoped;
- (void)baz
var methodScoped;
methodScoped = "function scope, declared with var";
anotherGlobal = "global scope, no var";
objectScoped = "still object scoped";
fileScoped = "still file scoped";
Accessor synthesizing is a way of reducing the amount of boilerplate code
you need to write for getting and setting instance variables. Take the following code block for example:
@implementation Person : CPObject
CPString firstName;
CPString lastName;
- (void)setFirstName:(CPString)aString
firstName = aString;
- (CPString)firstName
return firstName;
- (void)setLastName:(CPString)aString
lastName = aString;
- (CPString)lastName
return lastName;
With accessors, this can be shortened significantly:
@implementation Person : CPObject
CPString firstName
@accessors;
CPString lastName
@accessors;
Under the hood, variables declared with the @accessors keyword are automatically
assigned getter and setter methods. These methods may be overwritten if you need to do
some additional processing before returning the variable:
@implementation Person : CPObject
CPString firstName
@accessors;
CPString lastName
@accessors;
- (CPString)firstName
return [firstName capitalizedString];
// a silly example.
Additionally, you may configure your accessors to provide more friendly names
for your getters and setters than the underlying variable. The property argument
hides the underlying variable name and gives you a way of configuring the getter and setter method names:
@implementation Person : CPObject
CPString _firstName
@accessors(property=firstName);
CPString _lastName
@accessors(property=lastName);
This code would generate the methods firstName, setFirstName, lastName and setLastName.
You can also completely change the generated method names (often useful for Boolean accessors) by using the getter and setter arguments:
@implementation Person : CPObject
BOOL _cool
@accessors(getter=isCool, setter=setCool:);
For more information about @accessors you should read the
Objective-J 2.0
These language features are only available if you are running Cappuccino & 0.9.6.
Dictionary Literals
The syntax is @{ key: value, key2: value2, ... }, which is equivalent to the . Here’s an example:
return [CPDictionary dictionaryWithObjects:[[CPNull null], [CPNull null], 1.0, 3.0, CGSizeMakeZero(), 6.0, [CPNull null], CGSizeMakeZero()]
@"background-color",
@"border-color",
@"border-width",
@"corner-radius",
@"inner-shadow-offset",
@"inner-shadow-size",
@"inner-shadow-color",
@"content-margin"]];
@"background-color": [CPNull null],
@"border-color": [CPNull null],
@"border-width": 1.0,
@"corner-radius": 3.0,
@"inner-shadow-offset": CGSizeMakeZero(),
@"inner-shadow-size": 6.0,
@"inner-shadow-color": [CPNull null],
@"content-margin": CGSizeMakeZero(),
The format should be familiar from languages such as Python and, of course, JavaScript itself.
Regular JavaScript dictionaries will continue to work as normal.
// Objective-J Dictionary Literal
var a = @{ @"count": 2 };
// JavaScript Object
var a = { @"count": 2 };
Reference and Dereference
If you have programmed Objective-C, C or C++ you might think of an @ref reference as a JavaScript analog to a pointer. In C you might write:
int *aPtr = &a;
*aPtr = 5;
printf("%d\n", *aPtr);
// Prints 5.
printf("%d\n", a);
// Also prints 5.
Whereas in Objective-J you would use the @ref and @deref methods:
aRef = @ref(a);
@deref(aRef) = 5;
console.log(@deref(aRef));
// Logs 5.
console.log(a);
// Also logs 5.
Once you have a reference you can pass it around, save it, and dereference it as needed. It’s not an actual pointer though so pointer arithmetic is not possible. This is especially useful if you wish to have two return values. From CPNumberFormatter.j:
-(BOOL)getObjectValue:(id)anObjectRef forString:(CPString)aString errorDescription:(CPStringRef)anErrorRef
This method returns a BOOL to indicate whether the object value was a valid value. However, with this method you can also pass in a string for the errorDescription parameter which, in the case of an error, will be populated with a description of why the value was not valid:
var myError = @"",
isValid = [numberFormatter getObjectValue:someObject forString:someString errorDescription:@ref(myError)];
if (!isValid)
console.log("The value " + someString + " is not a valid! Error: " + @deref(myError));
Forward Class Declaration and Global Variables
One thing you may run into with Objective-J 2 is a circular dependency: class A imports class B, and somewhere in the import chain class A is imported. When that happens, the compiler will complain that it doesn’t recognize class A, because in fact the @implementation has not yet been parsed.
To solve a circular dependency, you have to use @class SomeClass to declare the class in one of the files.
For example CPObject.j uses CPString and CPException, but these cannot be imported since they need CPObject (a circular dependency). To avoid this circular dependency, you would “forward declare” these classes in CPObject:
@class CPString
@class CPException
The @global declaration is needed to tell the compiler about a variable that is not yet declared. For example CPObject.j uses the global variable CPInvalidArgumentException which is actually declared in CPException.j but cannot be used for the same reason as above. To use it, declare it at the top of your file:
@global CPInvalidArgumentException
Wrapping Up
This concludes our basic overview of Objective-J. The language is a
simple and straightforward addition to JavaScript, and most developers
shouldn’t have any trouble becoming familiar with it.
If you’d like to see the complete code listing from the tutorial, you
can download it all in a single file: .
Contribute
Get Answers
Project StatsKeyboard Shortcuts?
Next menu item
Previous menu item
Previous man page
Next man page
Scroll to bottom
Scroll to top
Goto homepage
Goto search(current page)
Focus search box
Change language:
Brazilian Portuguese
Chinese (Simplified)
stellt eine Kette von Zeichen dar indem ein Zeichen gleichbedeutend mit einem Byte ist. Das bedeutet, es gibt exakt 256 m?gliche Zeichen. Es impliziert zudem, dass PHP keine native Unterstützung von Unicode bietet. Siehe auch
zur Basis-Unicode Funktionalit?t.
Eine Zeichenkette () kann bis zu 2GB (maximal
bytes) gross werden.
Ein -Literal kann auf vier unterschiedliche Arten spezifiziert werden:
(since PHP 5.3.0)
Einfache Anführungszeichen
Der einfachste Weg einen
zu spezifizieren, ist ihn mit einfachen Anführungszeichen (das Zeichen ') zu umschliessen.
Um ein einfaches Anführungszeichen hierin anzugeben, fügen sie einen Backslash (\) vor dem Zeichen ein. Um einen Backslash vor einem einfachen Anführungszeichen im
oder am Ende des Strings zu verwenden, verdoppeln sie es (\\). Sollten vor ein beliebiges anderes Zeichen einen Backslash setzen, wird dieser mit ausgegeben.
Im Gegensatz zu den anderen Syntax werden
und Escape-Sequenzen für Sonderzeichen nicht maskiert (ersetzt) wenn sie in einem mit einfachen Anführungszeichen umschlossenen
erscheinen.
Doppelte Anführungszeichen
in doppelte Anführungszeichen (&) eingeschlossen wird, interpretiert PHP zus?tzliche Escape-Sequenzen für Sonderzeichen:
Maskierte Zeichen
Zeilenumbruch (LF or 0x0A (10) in ASCII)
Wagenrücklauf (CR or 0x0D (13) in ASCII)
horizontaler Tabulator (HT or 0x09 (9) in ASCII)
verticaler Tababulator (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
Seitenvorschub (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
Backslash (Rückstrich)
Dollar-Zeichen
doppelte Anführungszeichen
\[0-7]{1,3}
the sequence of characters matching the regular expression is a
character in octal notation
\x[0-9A-Fa-f]{1,2}
the sequence of characters matching the regular expression is a
character in hexadecimal notation
Wie bei s in einfachen Anführungszeichen wird beim maskieren aller anderen Zeichen der Backslash mit ausgegeben. Vor PHP 5.1.1 wurde der Rückstrich vor \{$var} nicht ausgegeben.
Das Expandieren von Varibalen-Namen ist eine der wichtigsten Besonderheiten von in doppelten Anführungszeichen angegebenen s. Siehe hierzu
für weitere Details.
Ein dritter Weg s zu begrenzen, stellt die Heredoc-Syntax dar: &&&. Nach diesem Operator wird ein beliebiger Bezeichner angegeben, dann eine neue Zeile. Hiernach folgt der eigentliche
und abschliessend erneut der Bezeichner um die Auszeichnung abzuschliessen.
Der schliessende Bezeichner muss in der ersten Spalte der Zeile beginnen. Zudem muss dieser sich an die selben Namensregeln wie jede andere Kennung in PHP halten: es darf nur alhpanumerische Zeichen und den Unterstrich enthalten und muss mit einem Buchstaben oder dem Unterstrich beginngen.
Es ist sehr wichtig, dass die Zeile mit dem schliessenden Bezeichner keine anderen Zeichen, ausser m?glicherweise einem Semikolon (;), enth?lt.
Das heisst insbesondere auch, dass der Bezeichner nicht eingerückt wird und auch keine Leerzeichen oder Tabulatoren vor oder nach dem Semikolon bestehen.
Zudem muss das erste Zeichen vor dem schliessenden Bezeichner eine neue Zeile sein, so wie sie vom Betriebssystem definiert wird.
In UNIX Systemen, auch Mac OS X, ist dies \n.
Auf den schliessenden Bezeichner (m?glicherweise gefolgt von einem Semikolon) muss zudem ebenfalls eine neue Zeile folgen.
Wenn diese Regel gebrochen wird und der schliessende Bezeichner nicht valide ist, wird er nicht als Bezeichner angenommen und PHP wird weiter nach einem solchen schliessenden Bezeichner suchen. Wird kein gültiger schliessender Bezeichner vor dem Dateiende gefunden, gibt PHP einen, auf die letzte Zeile der Datei zeigenden, Parser-Fehler aus.
Heredocs k?nnen nicht zur Initialisierung von Klassen-Eigenschaften benutzt werden. Benutzen Sie stattdessen .
Beispiel #1 Ungültiges Beispiel
&?phpclass&foo&{&&&&public&$bar&=&&&&EOTbarEOT;}?&
Heredoc text behaves just like a double-quoted , without
the double quotes. This means that quotes in a heredoc do not need to be
escaped, but the escape codes listed above can still be used. Variables are
expanded, but the same care must be taken when expressing complex variables
inside a heredoc as with s.
Beispiel #2 Heredoc string quoting example
&?php$str&=&&&&EODExample&of&stringspanning&multiple&linesusing&heredoc&syntax.EOD;/*&More&complex&example,&with&variables.&*/class&foo{&&&&var&$foo;&&&&var&$bar;&&&&function&foo()&&&&{&&&&&&&&$this-&foo&=&'Foo';&&&&&&&&$this-&bar&=&array('Bar1',&'Bar2',&'Bar3');&&&&}}$foo&=&new&foo();$name&=&'MyName';echo&&&&EOTMy&name&is&"$name".&I&am&printing&some&$foo-&foo.Now,&I&am&printing&some&{$foo-&bar[1]}.This&should&print&a&capital&'A':&\x41EOT;?&
Das oben gezeigte Beispiel erzeugt folgende
My name is &MyName&. I am printing some foo.
Now I am printing some Bar2.
This should print a capital 'A': \x41
Heredoc support was added in PHP 4.
Nowdocs are to single-quoted strings what heredocs are to double-quoted
strings. A nowdoc is specified similarly to a heredoc, but no
parsing is done inside a nowdoc. The construct is ideal for
embedding PHP code or other large blocks of text without the need for
escaping. It shares some features in common with the SGML
&![CDATA[ ]]& construct, in that it declares a
block of text which is not for parsing.
A nowdoc is identified with the same &&&
seqeuence used for heredocs, but the identifier which follows is enclosed in
single quotes, e.g. &&&'EOT'. All the rules for
heredoc identifiers also apply to nowdoc identifiers, especially those
regarding the appearance of the closing identifier.
Beispiel #3 Nowdoc string quoting example
&?php$str&=&&&&'EOD'Example&of&stringspanning&multiple&linesusing&nowdoc&syntax.EOD;/*&More&complex&example,&with&variables.&*/class&foo{&&&&var&$foo;&&&&var&$bar;&&&&function&foo()&&&&{&&&&&&&&$this-&foo&=&'Foo';&&&&&&&&$this-&bar&=&array('Bar1',&'Bar2',&'Bar3');&&&&}}$foo&=&new&foo();$name&=&'MyName';echo&&&&'EOT'My&name&is&"$name".&I&am&printing&some&$foo-&foo.Now,&I&am&printing&some&{$foo-&bar[1]}.This&should&not&print&a&capital&'A':&\x41EOT;?&
Das oben gezeigte Beispiel erzeugt folgende
My name is &$name&. I am printing some $foo-&foo.
Now, I am printing some {$foo-&bar[1]}.
This should not print a capital 'A': \x41
Unlike heredocs, nowdocs can be used in any static data context. The
typical example is initializing class members or constants:
Beispiel #4 Static data example
&?phpclass&foo&{&&&&public&$bar&=&&&&'EOT'barEOT;}?&
Nowdoc support was added in PHP 5.3.0.
Variable parsing
is specified in double quotes or with heredoc,
are parsed within it.
There are two types of syntax: a
The simple syntax is the most common and convenient. It provides a way to
embed a variable, an
value, or an
property in a
with a minimum of effort.
The complex syntax was introduced in PHP 4, and can be recognised by the
curly braces surrounding the expression.
Simple syntax
If a dollar sign ($) is encountered, the parser will
greedily take as many tokens as possible to form a valid variable name.
Enclose the variable name in curly braces to explicitly specify the end of
Similarly, an
index or an
can be parsed. With array indices, the closing square bracket
(]) marks the end of the index. The same rules apply to
object properties as to simple variables.
For anything more complex, you should use the complex syntax.
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it
allows for the use of complex expressions.
In fact, any value in the namespace can be included in a
with this syntax. Simply write the expression the same
way as it would appeared outside the , and then wrap it
in { and }. Since
{ can not be escaped, this syntax will only be
recognised when the $ immediately follows the
{. Use {\$ to get a literal
{$. Some examples to make it clear:
Functions and method calls inside {$} work since PHP 5.
String access and modification by character
Characters within s may be accessed and modified by
specifying the zero-based offset of the desired character after the
using square
brackets, as in
$str[42]. Think of a
of characters for this purpose.
s may also be accessed using braces, as in
$str{42}, for the same purpose. However, this syntax is
deprecated as of PHP 6. Use square brackets instead.
Beispiel #5 Some string examples
&?php//&Get&the&first&character&of&a&string$str&=&'This&is&a&test.';$first&=&$str[0];//&Get&the&third&character&of&a&string$third&=&$str[2];//&Get&the&last&character&of&a&string.$str&=&'This&is&still&a&test.';$last&=&$str[strlen($str)-1];&//&Modify&the&last&character&of&a&string$str&=&'Look&at&the&sea';$str[strlen($str)-1]&=&'e';?&
Accessing variables of other types using [] or
{} silently returns NULL.
Useful functions and operators
s may be concatenated using the '.' (dot) operator. Note
that the '+' (addition) operator will not work for this.
more information.
There are a number of useful functions for
manipulation.
general functions, and the
for advanced find & replace functionality.
There are also , and
functions to encrypt/decrypt strings
Finally, see also the .
Converting to string
A value can be converted to a
(string) cast or the
conversion is automatically done in the scope of an
expression where a
is needed. This happens when using the
functions, or when a
variable is compared to a . The sections on
the following clearer. See also the
TRUE value is converted to the
FALSE is converted to
&& (the empty string). This allows conversion back and
forth between
is converted to a
representing the number textually (including the
exponent part for s). Floating point numbers can be
converted using exponential notation (4.1E+6).
The decimal point character is defined in the script's locale (category
LC_NUMERIC). See the
s are always converted to the
&Array&; because of this,
can not by themselves show the contents of an
. To view a single element, use a construction such as
echo $arr['foo']. See below for tips on viewing the entire
s in PHP 4 are always converted to the
&Object&. To print the values of object members for
debugging reasons, read the paragraphs below. To get an object's class name,
function. As of PHP 5, the
method is used when
applicable.
s are always converted to s with the
structure &Resource id #1&, where 1 is
the unique number assigned to the
by PHP at runtime. Do
not rely it is subject to change. To get a
's type, use the
NULL is always converted to an empty string.
As stated above, directly converting an ,
not provide any useful information about the value beyond its type. See the
more effective means of inspecting the contents of these types.
Most PHP values can also be converted to s for permanent
storage. This method is called serialization, and is performed by the
function. If the PHP engine was built with
support, PHP values can also be
serialized as well-formed XML text.
String conversion to numbers
is evaluated in a numeric context, the resulting
value and type are determined as follows.
will be evaluated as a
contains any of the characters '.', 'e', or 'E'. Otherwise, it will be
evaluated as an .
The value is given by the initial portion of the . If the
starts with valid numeric data, this will be the value
used. Otherwise, the value will be 0 (zero). Valid numeric data is an
optional sign, followed by one or more digits (optionally containing a
decimal point), followed by an optional exponent. The exponent is an 'e' or
'E' followed by one or more digits.
For more information on this conversion, see the Unix manual page for
strtod(3).
To test any of the examples in this section, cut and paste the examples and
insert the following line to see what's going on:
Do not expect to get the code of one character by converting it to integer,
as is done in C. Use the
functions to convert between ASCII codes and
characters.
The documentation does not mention, but a closing semicolon at the end of the heredoc is actually interpreted as a real semicolon, and as such, sometimes leads to syntax errors.This works:&?php$foo = &&&ENDabcdEND;?&This does not:&?phpfoo(&&&ENDabcdEND;);?&Without semicolon, it works fine:&?phpfoo(&&&ENDabcdEND);?&
To save Your mind don't read previous comments about dates& ;)When both strings can be converted to the numerics (in ("$a" & "$b") test) then resulted numerics are used, else FULL strings are compared char-by-char:&?phpvar_dump('1.22' & '01.23'); var_dump('1.22.00' & '01.23.00'); var_dump('1-22-00' & '01-23-00'); var_dump((float)'1.22.00' & (float)'01.23.00'); ?&
Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the string:
$string = 'a';
var_dump($string[2]);& // string(0) ""
var_dump($string[7]);& // string(0) ""
$string[7] === '';& // TRUE
It appears that anything past the end of the string gives an empty string..& However, when E_NOTICE is on, the above examples will throw the message:
Notice:& Uninitialized string offset:& N in FILE on line LINE
This message cannot be specifically masked with @$string[7], as is possible when $string itself is unset.
isset($string[7]);& // FALSE
$string[7] === NULL;& // FALSE
Even though it seems like a not-NULL value of type string, it is still considered unset.
Here is an easy hack to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls:&?phpfunction _expr($v) { return $v; }$_expr = '_expr';define('qwe', 'asd');define('zxc', 5);$a=3;$b=4;function c($a, $b) { return $a+$b; }echo "pre {$_expr(1+2)} post\n"; echo "pre {$_expr(qwe)} post\n"; echo "pre {$_expr(c($a, $b)+zxc*2)} post\n"; ?&
Leading zeroes in strings are (least-surprise) not treated as octal.Consider:& $x = "0123"& + 0;&& & $y = 0123 + 0;& echo "x is $x, y is $y";& & //prints& "x is 123, y is 83"in other words: * leading zeros in numeric literals in the source-code are interpreted as "octal", c.f. strtol(). * leading zeros in strings (eg user-submitted data), when cast (implicitly or explicitly) to integer are ignored, and considered as decimal, c.f. strtod().
Although current documentation says 'A string literal can be specified in four different ways: ...', actually there is a fifth way to specify a (binary) string: &?php $binary = b'This is a binary string'; ?&The above statement declares a binary string using the 'b' prefix, which is available since PHP 5.2.1. However, it will only have effect as of PHP 6.0.0, as noted on
easy transparent solution for using constants in the heredoc format:DEFINE('TEST','TEST STRING');$const = get_defined_constants();echo &&&END{$const['TEST']}END;Result:TEST STRING
I recently discovered the joys of using heredoc with sprintf and positions. Useful if you want some code to iterate, you can repeat placeholders.
function getNumber($num = 0) {
& & $foo = rand(1,20);
& & return ($foo + $num);
}
function getString() {
& & $foo = array("California","Oregon","Washington");
& & shuffle($foo);
& & return $foo[0];
}
function getDiv() {
& & $num = getNumber();
& & $div = sprintf( "&div&%s&/div&", getNumber(rand(-5,5)) );
& & return $div;
}
$string = &&&THESTRING
I like the state of %1\$s &br /&
I picked: %2\$d as a number, &br /&
I also picked %2\$d as a number again &br /&
%3\$s&br /&
%3\$s&br /&
%3\$s&br /&
%3\$s&br /&
%3\$s&br /&
THESTRING;
$returnText = sprintf(& $string, getString(),getNumber(),getDiv()& );
echo $returnText;
Expected output of the above code:
I like the state of Oregon
I picked: 15 as a number,
I also picked 15 as a number again
5
You can use the complex syntax to put the value of both object properties AND object methods inside a string.& For example...&?phpclass Test {& & public $one = 1;& & public function two() {& & & & return 2;& & }}$test = new Test();echo "foo {$test-&one} bar {$test-&two()}";?&Will output "foo 1 bar 2".However, you cannot do this for all values in your namespace.& Class constants and static properties/methods will not work because the complex syntax looks for the '$'.&?phpclass Test {& & const ONE = 1;}echo "foo {Test::ONE} bar";?&This will output "foo {Test::one} bar".& Constants and static properties require you to break up the string.
If you want to use a variable in an array index within a double quoted string you have to realize that when you put the curly braces around the array, everything inside the curly braces gets evaluated as if it were outside a string.& Here are some examples:&?php$i = 0;$myArray[Person0] = Bob;$myArray[Person1] = George;echo "{$myArray['Person'.$i++]}&br&";echo "{$myArray['Person'.$i]}&br&";echo "{$myArray["Person{$i}"]}&br&";echo "{$myArray['Person$i']}&br&";echo "{$myArray['Person'$i]}&br&";?&
Use caution when you need white space at the end of a heredoc. Not only is the mandatory final newline before the terminating symbol stripped, but an immediately preceding newline or space character is also stripped.For example, in the following, the final space character (indicated by \s -- that is, the "\s" is not literally in the text, but is only used to indicate the space character) is stripped:$string = &&&EOTthis is a string with a terminating space\sEOT;In the following, there will only be a single newline at the end of the string, even though two are shown in the text:$string = &&&EOTthis is a string that must befollowed by a single newlineEOT;
You may use heredoc syntax to comment out large blocks of code, as follows:&?php&&&_EOC& & // end-of-line comment will be masked... so will regular PHP:& & echo ($test == 'foo' ? 'bar' : 'baz'); & & /* c-style comment will be masked, as will other heredocs (not using the same marker) */& & echo &&&EOHTMLThis is text you'll never see!& & & & EOHTML;& & function defintion($params) {& & & & echo 'foo';& & }& & class definition extends nothing& && {& & && function definition($param) {& & & & & echo 'do nothing';& & && }& & && & & }& & how about syntax errors?; = gone, I bet._EOC;?&Useful for debugging when C-style just won't do.& Also useful if you wish to embed Perl-like Plain Old D extraction between POD markers is left as an exercise for the reader.Note there is a performance penalty for this method, as PHP must still parse and variable substitute the string.
If you want a parsed variable surrounded by curly braces, just double the curly braces:
&?php
& $foo = "bar";
& echo "{{$foo}}";
?&
will just show {bar}. The { is special only if followed by the $ sign and matches one }. In this case, that applies only to the inner braces. The outer ones are not escaped and pass through directly.
I commented on a php bug feature request for a string expansion function and figured I should post somewhere it might be useful:using regex, pretty straightforward:&?phpfunction stringExpand($subject, array $vars) {& & foreach ($vars as $name =& $value) {& & & & $subject = preg_replace(sprintf('/\$\{?%s\}?/', $name), $value,$subject);& & }& & return $subject;}?&using eval() and not limiting access to only certain variables (entire current symbol table including [super]globals):&?phpfunction stringExpandDangerous($subject, array $vars = array(), $random = true) {& & & & & & extract($vars);& & & & & & & & $delim;& & & & if ($random)& & & & & & $delim = '___' . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . '___';& & & & else& & & & & & $delim = '__ASDFZXCV1324ZXCV__';& $statement = "return &&&$delim\n\n" . $subject . "\n$delim;\n";& & & & & & & & $result = eval($statement);& & & & & & & & if ($result === false)& & & & & & throw new EvalException($statement);& & & & & & & & return $result;& & }?&I hope that helps someone, but I do caution against using the eval() route even if it is tempting.& I don't know if there's ever a truely safe way to use eval() on the web, I'd rather not use it.
So you want to get the last character of a string using "String access and modification by character"?& Well negative indexes are not allowed so $str[-1] will return an empty string.&?php$str = 'This is a test.';$last = $str[-1];& & & & & & & & & $realLast = $str[strlen($str)-1];& $substr = substr($str,-1);& & & && echo '&pre&';var_dump($last);var_dump($realLast);var_dump($substr);
String conversion to numbers.Unfortunately, the documentation is not correct.<>It is not said and is not shown in examples throughout the documentation that, while converting strings to numbers, leading space characters are ignored, like with the strtod function.&?php& & echo "& && \v\f& & \r&& 1234" + 1;& & var_export ("\v\f& & \r&& 1234" == "1234");& & ?&However, PHP's behaviour differs even from the strtod's. The documentation says that if the string contains a "e" or "E" character, it will be parsed as a float, and suggests to see the manual for strtod for more information. The manual says<
Heredoc literals delete any trailing space (tabs and blanks) on each line. This is unexpected, since quoted strings do not do this. This is probably done for historical reasons, so would not be considered a bug.
I encountered the odd situation of having a string containing unexpanded escape sequences that I wanted to expand, but also contained dollar signs that would be interpolated as variables.& "$5.25\n", for example, where I want to convert \n to a newline, but don't want attempted interpolation of $5.Some muddling through docs and many obscenties later, I produced the following, which expands escape sequences in an existing string with NO interpolation.&?phpfunction expand_escape($string) {& & return preg_replace_callback(& & & & '/\\\([nrtvf]|[0-7]{1,3}|[0-9A-Fa-f]{1,2})?/',& & & & create_function(& & & & & & '$matches',& & & & & & 'return ($matches[0] == "\\\\") ? "" : eval( sprintf(\'return "%s";\', $matches[0]) );'& & & & ),& & & & $string& & );}$before = 'Quantity:\t500\nPrice:\t$5.25 each';$after = expand_escape($before);var_dump($before, $after);?&
Unlike bash, we can't do & echo "\a"& & && #beep!Of course, that would be rather meaningless for PHP/web, but it's useful for PHP-CLI. The solution is simple:& echo "\x07"
As of (at least) PHP 5.2, you can no longer convert an object to a string unless it has a __toString method. Converting an object without this method now gives the error:PHP Catchable fatal error:& Object of class &classname& could not be converted to string in &file& on line &line&Try this code to get the same results as before:&?phpif (!is_object($value) || method_exists($value, '__toString')) {& & $string = (string)$value;} else {& & $string = 'Object';}?&
Simple function to create human-readably escaped double-quoted strings for use in source code or when debugging strings with newlines/tabs/etc.&?phpfunction doubleQuote($str) {& & $ret = '"';& & for ($i = 0, $l = strlen($str); $i & $l; ++$i) {& & & & $o = ord($str[$i]);& & & & if ($o & 31 || $o & 126) {& & & & & & switch ($o) {& & & & & & & & case 9: $ret .= '\t';& & & & & & & & case 10: $ret .= '\n';& & & & & & & & case 11: $ret .= '\v';& & & & & & & & case 12: $ret .= '\f';& & & & & & & & case 13: $ret .= '\r';& & & & & & & & default: $ret .= '\x' . str_pad(dechex($o), 2, '0', STR_PAD_LEFT);& & & & & & }& & & & } else {& & & & & & switch ($o) {& & & & & & & & case 36: $ret .= '\$';& & & & & & & & case 34: $ret .= '\"';& & & & & & & & case 92: $ret .= '\\\\';& & & & & & & & default: $ret .= $str[$i];& & & & & & }& & & & }& & }& & return $ret . '"';}?&
If you need to emulate a nowdoc in PHP & 5.3, try using HTML mode and output capturing. This way '$' or '\n' in your string won't be a problem anymore (but unfortunately, '&?' will be).&?phpob_start(); ?&& A text with 'quotes' & & and $$$dollars$$$.&?php $input = ob_get_contents(); ob_end_clean();echo "&pre&" . $input . "&/pre&";?&
Hi.I noticed that the documentation does not mention that when you have an XML element which contains a dash (-) in its name can only be accessed using the bracelets notation.For example:&xml version="1"&&root&&& &element-one&value4element-one&/element-one&&/root&to access the above 'element-one' using SimpleXML you need to use the following:$simpleXMLObj-&root-&{'element-one'}to retrieve the value.Hope this helps,Denis R.
Regarding the lack of complex expression interpolation, just assign an identity function to a variable and call it:function id($arg) { return $ }$expr =echo "Field is: {$expr( "1 ". ucfirst('whatzit')) }"; It is slower due to an additional function call, but it does avoid the assignment of a one-shot temporary variable. When there are a lot of very simple value transformations made just for display purposes, it can de-clutter code.
Just want to mention that if you want a literal { around a variable within a string, for example if you want your output to be something like the following:{hello, world}and all that you put inside the {} is a variable, you can do a double {{}}, like this:$test = 'hello, world';echo "{{$test}}";
watch out when comparing strings that are numbers. this example:&?php$x1 = '111111';$x2 = '111112';echo ($x1 == $x2) ? "true\n" : "false\n";?&will output "true", although the strings are different. With large integer-strings, it seems that PHP compares only the integer values, not the strings. Even strval() will not work here.To be on the safe side, use:$x1 === $x2
Just some quick observations on variable interpolation:Because PHP looks for {? to start a complex variable expression in a double-quoted string, you can call object methods, but not class methods or unbound functions.This works:&?phpclass a {& & function b() {& & & & return "World";& & }}$c = new a;echo "Hello {$c-&b()}.\n"?&While this does not:&?phpfunction b() {& & return "World";}echo "Hello {b()}\n";?&Also, it appears that you can almost without limitation perform other processing within the argument list, but not outside it.& For example:&?$true =define("HW", "Hello World");echo "{$true && HW}";?&gives: Parse error: parse error, unexpected T_BOOLEAN_AND, expecting '}' in - on line 3There may still be some way to kludge the syntax to allow constants and unbound function calls inside a double-quoted string, but it isn't readily apparent to me at the moment, and I'm not sure I'd prefer the workaround over breaking out of the string at this point.
A note on the heredoc stuff.
If you're editing with VI/VIM and possible other syntax highlighting editors, then using certain words is the way forward.& if you use &&&HTML for example, then the text will be hightlighted for HTML!!
I just found this out and used sed to alter all EOF to HTML.
JAVASCRIPT also works, and possibly others.& The only thing about &&&JAVASCRIPT is that you can't add the &script& tags..,& so use HTML instead, which will correctly highlight all JavaScript too..
You can also use EOHTML, EOSQL, and EOJAVASCRIPT.
The docs say: "Heredoc text behaves just like a double-quoted string, without the double quotes" but there is a notable hidden exception to that rule: the final newline in the string (the one before closing heredoc token) is elided. i.e. if you have:$foo = &&&EOFabcEOF;the result is equivalent to "a\nb\nc", NOT "a\nb\nc\n" like the docs imply.
Empty strings seem to be no real strings, because they behave different to strings containing data. Here is an example.It is possible to change a character at a specific position using the square bracket notation:&?php$str = '0';$str[0] = 'a';echo $str."\n"; ?&It is also possible to change a character with does not exist, if the index is "behind" the end of the string:&?php$str = '0';$str[1] = 'a';echo $str."\n"; ?&But if you do that on an empty string, the string gets silently converted into an array:&?php$str = '';$str[0] = 'a';echo $str."\n"; ?&
Watch out for the "unexpected T_SL" error.& This appears to occur when there is white space just after "&&&EOT" and since it's white space it's real hard to spot the error in your code.
error control operator (@) with heredoc syntax:the error control operator is pretty handy for supressing minimal errors or omissions. For example an email form that request some basic non mandatory information to your users. Some may complete the form, other may not. Lets say you don't want to tweak PHP for error levels and you just wish to create some basic template that will be emailed to the admin with the user information submitted. You manage to collect the user input in an array called $form:&?php$mailer = new SomeMailerLib();$mailer-&from = ' System &&';$mailer-&to = '';$mailer-&subject = 'New user request';$mailer-&body = @&&&FORMFirstname = {$form['firstname']}Lastname = {$form['lastname']}Email = {$form['email']}Telephone = {$form['telephone']}Address = {$form['address']}FORM;?&
Expectedly &?php $string[$x] ?& and &?php substr($string, $x, 1) ?& will yield the same result... normally!
However, when you turn on the& Function Overloading Feature (), this might not be true!
If you use this Overloading Feature with 3rd party software, you should check for usage of the String access operator, otherwise you might be in for some nasty surprises.
$my_int = "12,140";echo& 1 + $my_Returns 13 not the expected 12141
If you require a NowDoc but don't have support for them on your server -- since your PHP version is less than PHP 5.3.0 -- and you are in need of a workaround, I'd suggest using PHP's __halt_compiler() which is basically a knock-off of Perl's __DATA__ token if you are familiar with it.Give this a run to see my suggestion in action:&?php$nowDoc = file_get_contents(__FILE__,null,null,__COMPILER_HALT_OFFSET__);$nowDoc=highlight_string($nowDoc,true);echo &&&EOF&!doctype html&&html&&head&&meta http-equiv="content-type" content="text/ charset=UTF-8" /&&title&NowDoc support for PHP & 5.3.0&/title&&meta name="author" content="Ultimater at gmail dot com" /&&meta name="about-this-page"content="Note that I built this code explicitly for thephp.net documenation for demonstrative purposes." /&&style type="text/css"&body{text-align:}table.border{background:#e0margin:1padding:1}table.border td{padding:5border:1px solid #8880text-align:background-color:#}code ::selection{background:#5f5color:}code ::-moz-selection{background:#5f5;color:}a{color:#33a;text-decoration:}a:hover{color:rgb(3,128,252);}&/style&&/head&&body&&h1 style="margin:1"&&ahref=""&Example #8 Simple syntax example&/a&&/h1&&table class="border"&&tr&&td&$nowDoc&/td&&/tr&&/table&&/body&&/html&EOF;__halt_compiler();&?php$juices = array("apple", "orange", "koolaid1" =& "purple");echo "He drank some $juices[0] juice.".PHP_EOL;echo "He drank some $juices[1] juice.".PHP_EOL;echo "He drank some juice made of $juice[0]s.".PHP_EOL; echo "He drank some $juices[koolaid1] juice.".PHP_EOL;class people {& & public $john = "John Smith";& & public $jane = "Jane Smith";& & public $robert = "Robert Paulsen";& & & & public $smith = "Smith";}$people = new people();echo "$people-&john drank some $juices[0] juice.".PHP_EOL;echo "$people-&john then said hello to $people-&jane.".PHP_EOL;echo "$people-&john's wife greeted $people-&robert.".PHP_EOL;echo "$people-&robert greeted the two $people-&smiths."; ?&
It may be obvious to some, but it's convenient to note that variables _will_ be expanded inside of single quotes if these occur inside of a double-quoted string.& This can be handy in constructing exec calls with complex data to be passed to other programs.& e.g.:$foo = "green";echo "the grass is $foo";the grass is greenecho 'the grass is $foo';the grass is $fooecho "the grass is '$foo'";the grass is 'green'
gtisza at gmail dot comYou incorrectly stated that thee documentation doesn't refer anything about the semicolon at the end of the heredocs and nowdocs& being interpreted as a "real" semicolon.If you read carefully, you will notice this, in the 1st sentence of the warning about heredocs:"It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;)."Interesting...It is refering about semicolons...But wait, there is more:1st sentence says:"As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement."So, here says that semicolons are statement separators, basicly...So, if you put a "real" semicolon at the end of these examples:&?php& & $a=5;& & $foo="String";& & $bar=array();& & $yep=null;& & $other=func();?&Why shouldn't you put at the end of heredocs and nowdocs?After all, a heredoc or a nowdoc is simply a string.You should read more carefully the documentation first before saying any comment.About serious questions:I didn't read all comments here, but you can run functions inside strings and heredocs.And you can even nest them inside {}Example:&?php& & $f=function($x){$a=func_get_args();unset($a[0]);return call_user_func_array($x,$a);};& & $d=0;& & echo $b=&&&NUMBERS4.0909 rounded is: {$f('round',4.0909,$d)}Time now is: {$f('time')}Nested heredocs/nowdocs: {$f('sprintf',&&&OTHERHere is an %s of nested %sOTHER,"Example",&&&'NOW'heredocs and nowdocsNOW)}NUMBERS;?&It's not pretty, and is hard to read, but sometimes it is useful to confuse curious people (like minifying the code).Warning: if any function that runs inside a string or heredoc gives a fatal error, the script MAY continue!
Note that :&?phpecho 'error' == 0, '&br&'; echo 'error' == '0', '&br&'; echo '0' == 0, '&br&'; ?&
An interesting finding about Heredoc "syntax error, unexpected $end".I got this error because I did not use the php close tag "?&" and I had no code after the heredoc code.foo1.php code gives "syntax error, unexpected $end".But in foo2.php and foo3.php, when you add a php close tag or when you have some more code after heredoc it works fine.Example Code:foo1.php1. &?php2. $str = &&&EOD3. Example of string4. spanning multiple lines5. using heredoc syntax.6. EOD;7. foo2.php1. &?php2. $str = &&&EOD3. Example of string4. spanning multiple lines5. using heredoc syntax.6. EOD;7. 8. echo $str;9.foo3.php1. &?php2. $str = &&&EOD3. Example of string4. spanning multiple lines5. using heredoc syntax.6. EOD;7. ?&
Small note to consider in heredoc multiple dimension array will not work and neither will any native language functions&?php$a[1] = "man";$b['man'] = "player";echo &&&ED$b[$a[1]] // will result in errorsubstr($a[1], 1) // will result in substr(man, 1)ED; ?&
In Example #8, above, consider the risk to the script if a programmer were to define('koolaid1', 'XYZ');& For this reason it's wise to use quotes around literal-string associative array keys.& As written without quotes, PHP should raise a Notice.}

我要回帖

更多关于 person是什么意思 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信